0% found this document useful (0 votes)
10 views20 pages

Python Basics: Variables, Loops, and Functions

python for begginers

Uploaded by

kannanabishek115
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views20 pages

Python Basics: Variables, Loops, and Functions

python for begginers

Uploaded by

kannanabishek115
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON

Python is an interpreter language.


(compiler mean it will execute the program at last, were as interpreter will
execute step by step line of code)

VARIABLE AND DATATYPE:


VARIABLE: it is nothing but a container to store something
Eg: a=10
b=20
(here both A and B are variable)
DATATYPE: data type is the type of the data
Eg: a=10
(here the datatype of the A is “integer”)
OPERATOR: operators are used for addition, subtraction, multiplication and
etc.,
Eg: a=10
b=20
c=a+b ----(1)
(in (1) “=” and “+” are the operators)
CASTING: converting one datatype into another datatype
Let’s take an example:
Here the output came as an “1020” because we given the input as an
“string”.

To change the string to the integer we are using the type casting ie.

Here the output came as “30” because we changed the datatype.

GETTING INPUT FROM THE USER:


For Getting an input from the user we just have to leave the variable as it is and
then we should declare the datatype
QUESTION 1: ANSWER:

QUESTION 2: ANSWER:

QUESTION 3: ANSWER:
IF ELSE:
Its is a type of conditional statement where it will check the first condition, if
satisfy it will give the corresponding output, else it will give other output.
Eg:

Here print statement should be inside the if condition, if not it the computer will
take the print statement as an separate print statement.
The “==” refers to checking or comparision operator. It will check wheather
both LHS and RHS are equal and then it will choose the output according to the
input.
QUESTION 4:

ANSWER:

QUESTION 5:

ANSWER:
ELIF :
In “if else” condition if there was many “if” statement then it will check all the
“if” statement even if correct statement is occuried to avoid this , “Elif”
condition is used.
In “elif” even if there are many “if” statement if the condition is satisfied it will
not execute any other statement.
e.g:
QUESTION 6:

ANSWER:

(In the above question there are many “if” statement soo we are using the elif
statement)
QUESTION 7:

ANSWER:

QUESTION 8:

ANSWER:
NESTED IF:
In “Nestedif” the “if statement ” will contain another if statement.
e.g.
QUESTION 9:

ANSWER:

FOR LOOP:
“for loop” is used to do something repeatedly untill the condition is satisfied.
In the for loop we will use another this called “range”.
for i in range(initial value, final value):
print(i)
if we use this we will get an output from the give range
e.g. if range(1,5) output is 0,1,2,3
there is an another thing can be added in the range function called “step”
for i in range(initial, final, step):
print(i)
this step is used and the step range is 2 then it will print like
e.g. range(1,5,2) output is 0,2

SYNTAX:
for i in “apple”:
Print(i)
OUTPUT: a variable
p
p
l
e

another method in “for loop” is using the range.


SYNTAX:
for i in range(5):
print(i)
OUTPUT: 0
1
2
3
4
Here the output will come till 4 because the range is “4”, so the number will
start from “0”.

To print certain set of number in “for loop” we have to specify the range
e.g.
for i in range(1,5):
print(i)
OUTPUT: 1
2
3
4
(NOTE: the given range is (1,5) the output is from 1 to 4, it will come like that
only)
QUESTION 10:
Print 2 tables
PROGRAM:
for i in range(1,11):
print(i,”x2=”,i*2)
OUTPUT:

Here “i” is resposible for the number and “x2=” refers to this
“i*2” refers to the multiplication of 2.
QUESTION 11:
ANSWER:

(here in the range (a+1) is given because the output should be given within that
range).
QUESTION 12:

ANSWER:

QUESTION 13:

ANSWER:

QUESTION 14:
ANSWER:

In question 13 and 14 they asked to tell the count of the even number between
the certain range ,so we are using the “count” and we are assinging it as an “0”
so that the count will increase.
QUESTION 15:

ANSWER:

QUESTION 16:

ANSWER:

NESTED FOR LOOP:


“nested loop” is nothing but loop inside the loop.
QUESTION 17:

ANSWER:

Here in the 2nd step the “print()” is used to avoid this error.
The end=”” in the 4th step is used to avoid the below error.
JUMP STATEMENT:
There are two types of jump statement they are
 Break
 Continue
 Pass-it acts as place holder.
BREAK:
for i in range(1,10):
if(i==5):
break
print(i)
here the output will be like 1,2,3,4
(NOTE: this break statement will not execute after the “if” condition is satisfed)
CONTINUE:
for i in range(1,10):
if(i==5):
continue
print(i)
the output is 1,2,3,4,6,7,8,9
(NOTE: in this continue statement the program will leave the value given in the
“if” and then continue to print the “for”)
WHILE LOOP:
The while loop is used when the iteration is unknown.
QUESTION 18:

ANSWER:
QUESTION 19:

ANSWER:

QUESTION 20:

ANSWER:

PYTHON COLLECTION:
There are 4 types of collection of data types in python.
 List : it is a collection which is ordered and changeable. Allows duplicate
members.
 Tuples : it is the collection which is ordered and unchangable. Allows
duplicate members.
 Set : it is a collection which is unordered, unchangable,and unindexed.
No dupicate members.
 Dictionary : is a collection which is ordered and changeable. No
duplicate members.
LIST: [1,2,3,4]
List will be indicated in “[ ]”. In list there are many operations like append( ),
pop( ), extend( ), insert( )
Append( ): is used to add an value in the list, but it will only add at the end
position.
Syntax: [Link](5)
Pop( ): is used to delete the value in the list, and we can choose the position to
be deleted.
Syntax: [Link](5) here the (5) refers to the index number.
Extend( ): is used to combine two different list into one
Syntax: [Link](b)
Instert( ): is used to insert an value at any position.
Syntax: [Link](0,7) here 0 is position and 7 is value to be added.

TUPLE: (1,2,3,4)
Tuple is denoted with “( )”. it cannot be modified in the tupil and we cannot add
or remove values in tuple. It will allow duplicates.
We can change the tupil into list and then we can modify.
SYNTAX:
A=(1,2,3)
B=list(a)
Print(b)

SET:
Set is denoted with “{ }”. In set we can only add( ), pop( ), remove( ), update( )
(NOTE: sets are unordered and it will not allow duplicate value)
If we add, pop, remove or update we cannot tell where it will be modify.

DICTIONARY:
it is denoted with “{ }”.in dictionary there will be no [Link] we can
add( ), update( ), pop( ).
The syntax of the dictionary will be like “key value” pair.
A={“name” : “abi”}. Here “name” is “key” and “abi” is value of the key.
To “update” any key we can use the syntax: a[“age”]=2
We can use this same syntax to add any other key also.

FUNCTIONS:
Function is an essential building blocks that allows us to organise and reuse the
code. Funtcion are of 2 type “user-defind function” and “build in function”
BUILD-IN FUNCTION:
Build-in function are functions which is given by the python interpreter where
we can use them but cannot modify.
USER-DEFINED FUNCTION:
User-defined function are the function which is created by the user.
e.g.

ANSWER:

SYNTAX:
Here “def” is the most important keyword in a [Link] step 1 and 2 are
function. “The add( )” in step 3 is used to call a function.
QUESTION:

ANSWER:

QUESTION:

ANSWER:

In “def” and in “for” the range should be same and in the calling function the
variables should be different.

RETURN KEYWORD:
QUESTION:

ANSWER:

The simple trick here is use the usual callimg function and put “return” instead
of “print()” and while calling the function assign it with the variable and the
then print the variable.

CLASSES AND OBJECTS:


Class: is blueprint for an object. Creating an new class creates an new object.
Object: is instance of class. A class is like a blue print where object is an copy
of the blueprint.
QUESTION:

ANSWER:
CONSTRUCTOR:
Constructor is an inbuilt keyword and it is a unique function that’s gets called
automatically when an object is created of a class.
e.g. def __init__(self):
the main purpose of the comstructor is to initialise or assign values to data of
that class.
QUESTION:
ANSWER:

Here def __init__ (self): is an comstructor and the term “(self)” is mandatory we
have to put in every fuction.

TYPES OF VARIABLE IN CLASS:


There are 2 types of variable
 Class variable
 Instance variable
Class variable : are defined within class constructor
Instance variable : are declared in a class but outside of constructor, methods, or
blocks

POLYMORPHISM:
The word polymorphism means having many [Link] python polymorphism
means same function name being used in different types.

ENCAPSULATION:
In encapsulation data and methods are bundled together into a single package.

Common questions

Powered by AI

User-defined functions in Python are created by developers to perform specific tasks, promoting code reuse and organization. Defined with the 'def' keyword, they contrast with built-in functions, which are provided by the Python interpreter and cannot be altered. User-defined functions allow programmers to implement custom logic, while built-in functions offer ready-to-use functionality .

Type casting in Python involves converting a variable from one type to another, which is essential for data manipulation when different operations require specific types. For example, if a number is stored as a string '10', casting to an integer using int('10') allows arithmetic operations. An example is converting inputs '10' and '20' from strings to integers to perform addition, resulting in 30 instead of '1020' .

Python offers lists, tuples, sets, and dictionaries for managing collections, each with unique characteristics. Lists are ordered, mutable, and allow duplicates. Tuples are ordered, immutable, and also allow duplicates. Sets are unordered, immutable, and restrict duplicates. Dictionaries are ordered collections of key-value pairs, mutable, and disallow duplicate keys. These distinct properties make each collection type suitable for various data storage needs .

Constructors in Python are special methods, typically '__init__', automatically called when a new instance of a class is created. They initialize the object's state, setting initial values for attributes. Unlike regular methods, constructors focus on object setup and need specific syntax. An example is 'def __init__(self):', which assigns initial values like 'self.name = name'. Regular methods enable operations and manipulations on these attributes .

A Python interpreter executes code line-by-line, which means it processes the program incrementally. Unlike a compiler, which executes the entire program at once, an interpreter allows immediate detection of errors and interaction. This line-by-line execution can influence performance, as interpreted languages typically run slower compared to compiled ones because they do not translate the entire code into machine code ahead of time .

Encapsulation in Python bundles data and methods within a class, restricting direct access to object data. This is achieved using private variables and getter/setter methods, protecting data integrity by enforcing validation before modifications. It secures sensitive data, preventing unintended interference from outside the class and ensures controlled data interaction, thus maintaining program stability .

Polymorphism in Python allows functions to operate on different object types, promoting flexible and extensible code. It manifests when methods in different classes share the same name, enabling objects to be processed through a common interface. This reduces code complexity by allowing a single function to adapt to various input types, enhancing reusability and maintaining simplicity in object-oriented programming .

The 'return' keyword allows a function to send a result back to the caller, enabling function composition and further processing of the output. It differs from 'print', which simply displays result to the console without returning a value for further use. 'Return' facilitates value chaining and integrates function outputs in broader programs, leading to robust and reusable code .

The 'elif' statement in Python provides an efficient alternative to multiple 'if' statements by eliminating unnecessary condition checks once a preceding condition is met. This improvement means only one branch is executed, preventing redundant evaluation of all conditions. By using 'elif', program logic becomes clearer, and execution is optimized when dealing with mutually exclusive scenarios .

A 'while' loop is more suitable than a 'for' loop when the number of iterations is not known in advance. This loop type relies on a boolean condition to continue iteration, making it ideal for scenarios requiring indefinite loops or where iteration depends on dynamic runtime conditions, such as reading data from a file until an EOF condition is met .

You might also like