SlideShare a Scribd company logo
Python variables and data types
INTRODUCTION OF PYTHON VARIABLES…
• VARIABLE IS A NAME THAT IS USED TO REFER TO THE
MEMORY LOCATION
• PYTHON VARIABLE IS ALSO KNOWN AS IDENTIFIER TO USED
TO HOLD THE VALUE
• PYTHON VARIABLE NAMES CAN BE GROUP OF BOTH OF
LETTER AND DIGITS
• USE LOWER CASE LETTER AND UPPER CASE LETTER ARE
DIFFERENT LIKE RAHUL AND RAHUL
• THEY USE THE UNDERSCORE THE VARIABLE LIKE (_A) & (A_)
Python variables
Variable naming rules
Declaring variables
Multiple Assignment
Deleting variables
Python Variable Types
Variable naming rules
 The first character of variable must be an alphabet or underscore(_)
 All the character except the first character may be an alphabet of lower
case like(a-z),upper case like(A-Z) and they use the digits(0-9)
 Identifier name must not use any white space and special character
(!,@,#,%)
 Identifier name must not be similar any keyword
 Identifier name are case sensitive for example :- NAME and name are the
different name not a same variable
 Example of valid identifier name is :- _a,a123 etc
declaring variables
 Python does not bind us to declare a variable before using the validation
 It allow to create a variable at the required time
 We don’t need to declare explicitly variable
 We assign any value to the variable that variable declared
 The equal (=) operator is used to assign the value of variable
 Example :- A=10
A is a variable name and (=) use the assign the value and 10 is a value of A
Python variables
 Example of python variable:-
First Declare variable
Second add next variable
Finally print the variable values
A=10
B=10
C=A+B
Print(c)
Example of variable
Name=“sourav”
Age=23
Salary=21500
print(Name)
print(Age)
print(Salary)
Or
Print(Name,Age,Salary)
Multiple Assignment
 Python allows us to assign a value to multiple variable in a single statement
It is known as Multiple Assignment
 We can apply multiple assignment in two ways
 Either by assigning a single value to multiple variables or assigning a multiple value in
multiple variables
Assigning single value to multiple
variables
 Example:-
a=b=c=100
print(a)
print(b)
print(c)
User assign the multiple variable and assign the single value to multiple
variable
Like a and b and c variables value is 100
And next step is print the all values
Assigning multiple values to
multiple variables
 Example:-
a,b,c=10,20,30
print(a)
print(b)
print(c)
User assign the multiple variable and assign the multiple value
And second step print the all values
Deleting variables
 We can delete the variable use Del keyword
syntax:-
del<variable_name>
Example :-
x=5
print(x)
del x
print(x)
I print the variable x and assign the value and print the value after printing the
value Delete the variable x
Python variable types
They are the two types of variables in
python
First one is Local Variable
Second one is Global variable
Local variable
 The local variable is create under the function not define the outside of the
function .It is known as local variable and local scope
Local Variable Example :-
def sample():
y=“local”
print(y)
sample()
Global variable
 In python variable declare outside of the function in global scope is
known as global variable .
 This means that a global variable can accessed inside or outside of the
function
Example of Global Variable :-
x=“global”
def sample():
print(“x inside :-” ,x)
sample()
print(“x outside:-”,x)
Python data types
 Variable can hold value and every value has a data type
 We do not need the define the type of the variable while
declaring
Example:- a=5
 The variable a hold the integer value five
 User can not define any Data Type
 Python interpreter will automatically variable a given integer Data
Type
 Python provide the type () function to check the data type any
variable
Python data types
EXAMPLE OF CHECK THE DIFFERENT DATA TYPES:-
a=10
b=“Hi python”
c=10.5
Print(type(a))
Print(type(b))
Print(type(c))
Python data types chart
Python data types chart
 Python provides Various type of Data Types
1. Numbers
2. Sequence type
3. Boolean
4. Set
5. Dictionary
Number data type
 Number data type can store number values
 Integer float and complex value belong to number data type
 Python provide the type () function to check the any type of data type
variable
 Number Data Type divide into sum parts :-
1. Integer
2. Float
3. complex
Number data type
 Example of number data type like integer float and complex :-
a=5
print(“The type of a”, type(a))
b=40.5
print(“The type of b”, type(b))
c=1+3j
print(“The type of c”, type(c))
print(“c is a complex number “, is instance(1+3j,complex))
Definition of int float and complex data type
1) INT:-integer value is the value of number value like 10,20,30,40,50,5,4,3,2,1
python has no restriction on the length of an integer value
Example :- a=10
(a)<-- is a variable and user give the a variable value is 10
10 is a integer value .python by default check the data type
2) Float:- float data type store the value in floating-point number like
1.9,20.5,9.9902 it is accurate 15 decimal points
Example:- a=5.9
(a)<-- is a variable and user give the a variable value is 5.9
5.9 is a Float value .python by default check the data type
3) complex:-A complex number contains an ordered pair . complex number are written in
the form x + yj, where x is a real part and y is a imaginary part
Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part
Sequence type
 Sequence types divided into three parts
I. String
II. List
III. tuple
 String:- The string can be defined as the sequence of characters
python use single ,double and triple quotes to define a string.
string is a sequence of unique characters
string handling in python the operator + is used to concatenate the two
strings.
Sequence type
Example:-
“hello”+”python” returns hellopython
Example of string:-
str=“hello python“
print(str)
s=‘’’multiline
string’’’
print(s)
Sequence type
Example of string:-
str1=“hello javatpoint”
str2=“how are you”
print(str1[0:2])
print(str1[4])
print(str2[1*2])
print(str1+str2)
Sequence type
 List:- python list are similar to array in c .list can contain data of different
types .the items are stored in the list are separated with the comma (,) and
enclosed with the square brackets[].
 List:-list are use slice operator to access the data of the list. The
concatenation operator (+) and repetition operator(*) works with the same
way as they working with the string.
 List:- list contain all type of data types like int,float,string.
 List:-list are allowed duplicates elements.
 List:- list are mutable the user can modify elements are list.
 List:-list are start with [] square brackets.
Sequence type
 Example of list:-
list=[1,”hii”,python”,98765]
print(type(list))
print(list)
print(list[3:])
print(list[0:2])
print(list+list)
print(list*3)
Sequence type
Example of list:-
list = ["Jessa", "Kelly", 20, 35.75]
print(list)
print(type(list))
print(list[0])
print(list[1:5])
list[1] = "Emma"
print(list[1])
list2 = list(["Jessa", "Kelly", 20, 35.75])
print(list2)
Sequence type
 tuple data type:-A tuple is a similar to the list .list and tuple can contain the
collection of different data types .the items of the tuple are separated with
the comma(,) and enclosed with the parentheses().
 tuple data type:- Tuple are read only data . We can not modify any element
into the tuple .
 tuple data type:- Tuple are ordered collection of data .
 tuple data type:- Tuple are unchangeable
Example :- if you want to store the roll no of students that you don’t change
so you can use the Tuple data type
Sequence type
Example of Tuple Data type:-
my_tuple = (11, 24, 56, 88, 78)
print(my_tuple)
print(type(my_tuple))
print(my_tuple[2])
print(my_tuple[2:7])
my_tuple2 = tuple((10, 20, 30, 40))
print(my_tuple2)
Sequence type
Example of Tuple Data type:-
Reverse tuple;-
Tuple=(11,22,33,44,55,66,77)
Print(tuple[::-1]
dictionary
 Dictionary:-dictionary is an unordered set of key –value pair of items .key can
hold primitive data type and value is a arbitrary project.
 Dictionary:-dictionary are separated with the comma(,) as enclosed with the curly
braces {}
 Dictionary:- the dictionary type is represented using a Dict class .if you want to
store the name and roll no all students then you can use the Dict type
 Dictionary:-dictionary are duplicate keys are not allowed but the value can be
duplicate key the old value will be replaced with the new value
 Dictionary:- dictionary is a mutable which means we can modify the items
 Dictionary:- dictionary is unordered so we can’t perform indexing and slicing
dictionary
 Dictionary;-

abc={1:”sourav”,2:”sham”,3:”sunny”}
print(abc)
print(“1st name is “+abc[1])
print(“2nd name is “+abc[2])
print(abc.keys())
print(abc.values())
boolean
 Boolean:- Boolean type provides two built-in values, True and False. These
values are used to determine the given statement true or false.
 Boolean:-It denotes by the class bool. True can be represented by any non-
zero value or 'T' whereas false can be represented by the 0 or 'F'.
Exampleof booleAN:-
Print(type(true))
Print(type(false))
Print(false)
set
 set :- python set is the unordered collection of the data type.it is iterable ,
mutable(cannot modify after creation), and has unique elements.
 Set:- In set, the order of the elements is undefined; it may return the
changed sequence of the element.
 set;-The set is created by using a built-in function set(), or a sequence of
elements is passed in the curly braces and separated by the comma.
set
 The set data type has the following characteristics.
1. It is mutable which means we can change set items
2. Duplicate elements are not allowed
3. Heterogeneous (values of all data types) elements are allowed
4. Insertion order of elements is not preserved, so we can’t perform
indexing on a Set
set
Exampleof set:-
Set2={“sunny”,2,3,”python”}
Print(set2)
Set2.add(10)
Print(set2)
Set2.remove(2)
Print(set2)
set
 Exampleof set:-
my_set = {100, 25.75, "Jessa"}
print(my_set)
print(type(my_set))
my_set.add(300)
print(my_set)
my_set.remove(100)
print(my_set)
keywords
 Python keywords are special reserved words
that convey a special meaning to the
compiler/interpreter .
 Each Keywords has a special meaning and a
specific operation .
 These keywords can’t be used as a variable .
 Following is the list of python keywords.
keywords
keywords
 Consider the following explanation of keywords.
1. True - It represents the Boolean true, if the given condition is true, then it returns
"True". Non-zero values are treated as true.
2. False - It represents the Boolean false; if the given condition is false, then it returns
"False". Zero value is treated as false
3. None - It denotes the null value or void. An empty list or Zero can't be treated
as None.
4. and - It is a logical operator. It is used to check the multiple conditions. It returns true if
both conditions are true. Consider the following truth table.
5. or - It is a logical operator in Python. It returns true if one of the conditions is true
6. not - It is a logical operator and inverts the truth value.
keywords
 A B A and B
True True True
True False True
False True True
False False
False
Truth table
keywords
 7. assert - This keyword is used as the debugging tool in Python. It checks
the correctness of the code. It raises an AssertionError if found any error
in the code and also prints the message with an error.
 Example of assert:-
a=10
b=20
c=a+b
Print(“The value is :-”,d)
keywords
 8. Def :-The Def keyword is used to declare the function in python . They
use the Def keyword.
Example of Def keyword :-
def sample():
a=10
print(“The value is :-”,a)
sample()
keywords
 9. Class:- It is used to represent the class in python. The class is the
blueprint of the objects. It is the collection of the variable and methods
Example of the class :-
class parent:
variables…………..
def sample():
statements…….
keywords
 10. Continue:- The continue statement are used to stop the execution of
the current iteration.
Following example of continue statement:-
a=0
while a<4
a+=1
if a==2:
continue
print(a)
keywords
 11.Break:- The break statement are used to terminate the loop execution
and control transfer to end of the loop .
Example of break statement:-
for i in range(5):
if( i==3):
break
print(i)
print(“End of execution”)
keywords
 12. If Statement:- If statement is represent the conditional statement. The
execution of a particular block is decided by if statement .
 Example of If Statement:-
i=18
if(i<12):
print(“I am less than 18”)
keywords
 13. Else:-The else statement is used with the if statement .when if
statement returns false then else block are executed.
Example of Else statement:-
n=11
if (n%2==0):
print(“Even”)
else:
print(“odd”)
keywords
 14. Elif:- The Elif keyword is used to check the multiple conditions . it is short for else-if . If the
previous condition is false , then check until the true condition is found .
Example of Elif statement:-
marks = int(input("Enter the marks:"))
if(marks>=90):
print("Excellent")
elif(marks<90 and marks>=75):
print("Very Good")
elif(marks<75 and marks>=60):
print("Good")
else:
print("Average")
Python Operators
 The operator can be defined as a symbol which is responsible for a particular operation
between two operands.
 Operators are the pillars of a program on which the logic is built in a specific programming
language
 Example of python Operators:-
Operators
1. Arithmetic operators
2. Comparison operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators
 Arithmetic operators are used to perform arithmetic operations between
two operands.
 It includes + (addition), - (subtraction), *(multiplication), /(divide),
%(reminder), //(floor division), and exponent (**) operators.
 Example of Arithmetic operators:-
 A=20
 B=10
 C=a+b,a-b,a*b,a%b,a/b,a//b,a**b
 Print(c)
Python Operators
Comparison operator
 The name itself is explaining that this operator is used to compare
different things or values with one another.
 In Python, the Comparison operator is used to analyze either side of the
values and decides the relation between them.
 Comparison operator is also termed as a relational operator because it
explains the connection between them.
 Example of comparison operators:-
 A=20
 B=10
 C=a==b,a!=b,a>b,a<b,a>=b,a<=b
 Print(c)
Comparison operator
 Comparison operators are used to comparing the value of the two
operands and returns Boolean true or false accordingly.
Assignment Operators
 The assignment operators are used to assign the value of the right
expression to the left operand.
Assignment Operators
a=4
b=2
a+=b
Print(a)
A=4
B -=2
Print(a)
A=4
b *=2
Print(a)
Assignment Operators
a=4
a/=2
Print(a)
a=4
a **= 2
Print(a)
a=5
a %=2
Print(a)
a=4
a //=2
Print(a)
Bitwise Operators
 The bitwise operators perform bit by bit operation on the values of the
two operands.
Bitwise Operators
It performs logical AND operation on the integer value after converting an
integer to a binary value and gives the result as a decimal value it returns true
only if both operands are true otherwise it returns false
Example of Bitwise AND operators:-
a=7
b=4
c=5
Print(a&b)
Print(a&c)
Print(b&c)
Bitwise Operators
 Bitwise or operators:-
It performs logical OR operation on the integer value after converting integer
value to binary value and gives the result a decimal value . It returns false only if
both operands are true otherwise it returns true.
Example of Bitwise OR operators:-
a=7
b=4
c=5
Print(a | b)
Print(a | c)
Print(b| c)
Bitwise Operators
 Bitwise XOR operators:-
It performs logical XOR operation on the binary value of a integer and gives
the result as a decimal value.
Example of a Bitwise XOR operators:-
a=7
b=4
c=5
Print( a ^ c)
Print(b ^ c)
Bitwise Operators
 Bitwise 1’s complement ~:-
 It performs 1’s complements operation it invert each bit of binary value
and returns the bitwise negation of a value as a result.
Example of Bitwise 1’st complements:-
a=7
b=4
c=3
Print(~a, ~b, ~c)
Bitwise Operators
 Bitwise left-shift << operators:-
The left-shift << operators performs a shifting bit of a value by a given
number of the place and fills 0’s to new positions.
Example of Bitwise left-shift << operators:-
print(4 << 2)
print(5 << 3)
Bitwise Operators
 Bitwise right-shift >>
The left-shift >> operator performs sifting a bit of value to the right by a
given
Number of places.
Example of Bitwise right-shift >> operators:-
print(4 >> 2)
print(5 >> 2)
Membership operators
 Membership operators:- python membership operators are used to check
for membership of objects in sequence ,
 such as string , list , tuple. It checks whether the given value or variable is
present in a given sequence.
 If present it will return true else false.
 Python there are two membership operators IN and NOT IN
Membership operators
 IN operator:- it returns a result as true. If it finds a given object in the
sequence. Otherwise it return false.
 Example of IN OPERATORS:-
list[11,15,21,29,50,70]
num=15
If num in list:
print(“number in present”)
else:
print(“number not in present”)
Membership operators
 NOT IN OPERATOR:-it returns true if the object is not present in a given
sequence.
 Otherwise it return false.
 Example of NOT In OPERATOR:-
TUPLE(11,15,21,29,50,70)
num=15
If num not in tuple:
print(“number is present”)
else:
print(“number is not present”)
IDENTITY OPERATORS
 Identity operators check whether the value of two variable is the same or
not.
 This operator is known as reference - quality operators.
 Because the identity operators compares value according to two variable
memory addresses
 Python has 2 identity operators is and is not
IDENTITY OPERATORS
 IS OPERATOR:- this operator return Boolean true or false.
 It return true if the memory address first value is equal to the second value
otherwise it return false.
 Example of is operators:-
X=10
Y=11
Z=10
Print(x is y)
Print(x is z)
IDENTITY OPERATORS
 IS NOT OPERATORS: the is not operators return Boolean value either true
or false.
 It return true if the first value is not equal to the second value
 Otherwise it return false.
Example of is not operator:
X=10
Y=11
Z=10
Print(x is not y)
Print(x is not z)
Control flow statements
 The control flow statements are divided into three parts:-
1. Conditional statements
2. Iterative statements
3. Transfer statements
Control flow statements
Control flow statements
 Conditional statement:-
 The conditional statement are depending on whether a given condition is true
or false.
 You are execute different blocks of codes depending on the outcome of a
condition.
 Condition statements always evaluate to either true or false
 Types of conditional statements:-
1. if statements
2. If-else
3. If-elif-else
4. Nested if-else
Control flow statements
 Iterative statements:- iterative statement allow us to execute a block of code
repeatedly as long as the condition is true.
 We also call it a loop statements
 Python provides us to the following two loop statement to perform
Types of a iterative statements:-
1. For loop
2. While loop
Control flow statements
 Transfer statement:- in python transfer statement are used to alter(stop) the
program way of execution.
 The types of transfer statement:-
1. Break statement
2. Continue statement
3. Pass statement
Conditional statement
 If statement in python:-
In control statement the if statement is the simplest form.it takes a condition
and evaluate to either True or False
If the condition is true then the true block of code will be executed and if
condition is false then the block of code is skipped and controller moves the
next block of code like else block.
Syntax of if statement:-
If condition:
statement 1
statement 2
statement n
Conditional statement
 Flow chart of if else statement:-
If else statement
 Example of if else statement:-
num=5
if num >=0:
print(“number is positive”)
else:
print(“number is negative”)
If else statement
 Example of if else statement:-
Password=input(“Enter password:-)
If password==“Hello@5656”:
print(“correct password”)
else:
print(“invalid password”)
If-elif-else
 Flow chart of if elif else:-
If-elif-else
 If-elif-else codition statement has an elif blocks to chain multiple
conditions one after another.
 This is useful when you need to check multiple coditions.
 The if –elif-else we can make a tricky decision.
 The elif statement checks multiple conditions one by one and if the
condition fulfllls then execute the code.
If-elif-else
 Syntax of if elif else statement:-
If condition-1:
statement 1
elif condition-2:
statements2
elif condition-3:
statement 3
else:
statements
If-elif-else
Example of if leif else statement:-
num=3
If num >0:
print(“positive”)
elif num==0:
print(“zero”)
else:
print(“negative number”)
If-elif-else
 Example of if elif else statement:-
a=40
b=30
If b>a:
print(“b is greater then a”)
elif a==b:
print(“a and b are equal”)
else:
print(“a is greater then b”)
If –elif-else
 Example of if elif and else statement:-
a=50
If(a==20):
print(“value of a is 20”)
elif(a==30):
print(value of a is 30”)
elif (a==40)
print(“value of a is 40”)
else:
print(“value of a is greater then 40”)
Nested if else statement
 Nested if else statement:-in python nested if else statement is an if
statement inside the if else statement
 It is allowed in python to put any number of if statement in another if
statement.
 Indentation is the only way to different level nesting.
 We can have a if …elif …else statement inside another if elif ..else
statement this is called nesting in computer.
 Any number of these statement can be nested inside one another
Nested if else statement
 Flow chart of Nested if else statement:-
Nested if else statement
 Syntax of the nested-if else:
If condition outside:
if condition inside:
statement of inside if
else:
statement of inside else:
statement of outside if
else:
outside else
Statement outside if block
Nested if else statement
 Example of nested if else statement:-
a=int(input(“Enter 1st value:-”)
b=int(input(“Enter 2st value:-”)
If a>=b:
if a == b:
print(a ‘and’, b, ‘are equal’)
else:
print(a, ‘is greater then’, b)
else:
Print(a, ‘is smaller then’,b)
Nested if else statement
 Example of nested if else statement:-
num=int(input(“Enter a number:-”))
if num >=0:
print(“zero”)
else:
print(“positive number”)
else:
print(“negative number”)
For loops
 A for loop is used for iterating over a sequence that is either a list a tuple a
dictionary a set or a string.
 This is less like the for keyword in other programming language and work
more like an iterator method.
 For loop we can execute a set of statement once for each item in a list
tuple set etc.
 Syntax if for loop:-
 For iterating_var in sequence:
statement(s)
For loops
 Syntax of for loop:-
for I in range:
statement 1
statement 2
statement n
Syntax of for loop I in the iterating variable and the range specific how many
times the loop should run.
For example if a list contains 10 number the for loop will execute 10 times to
print each number.
Iteration of the loop the variable I get the current value.
For loops
 Flow chart of for loop:-
For loop with range()
For loop with range function
 The range function is used to generate the sequence of the numbers. If we
pass the range like (10) it will generate the sequence of the numbers from
0 to 9
 The syntax of the range function:-
Range(start , stop , step size)
Range(1,10,2)
 The start represents the beginning of the iteration.
 The stop represents that the loop will iterate till stop n-1 the range (1,10)
will generate numbers 1 to 9 iteration
 The step size is used to skip the specific numbers from the iteration it is
optional to use.by default the step size is 1 .
For loop with range function
 Example of range function of for loop:-
 for I in range(10):
print(I,end=“”)
 For I in range(1,10):
print(I,end=“”)
 For I in range(1,10,2):
print(I,end=“”)
For loop with range function
 Example of range function in for loop:-
a=int(input(“Enter any number:-”)
for i in range(1,11)
c=a*I
print(a,”X”,I”=“c)
Nested for loop in python
 Python allows us to nest any number of for loops inside a for loop . the
inner loop is executed n number of times for every iteration of the outer
loop
 Syntax of nested for loop
for I in range: #outer loop
for j in range : # inner loop
#statements
statements
Nested for loop in python
 Example of nested for loop:-
for I in range(0,6):
for j in range(i):
print(“*”,end=“ “)
print()
Nested for loop in python
 Example of nested for loop:-
for I in range(1,6):
for j in range(i):
print(i,end=“”)
print()
If else in for loop
 If else statement use in for loop.
 If else is a conditional statement for example print student names who got
more then 80 percent.
 If else statement check the condition and if the condition is true it execute
the block of code present inside the if block and if the condition is false it
will execute the block of code present inside the else block.
 If else condition is used inside the loop the interpreter check the if
condition in each iteration and the true condition is run and false
condition is skkiped.
If else in for loop
 Syntax of if else statement in for loop:-
for i in range(--):
if condition:
statements
else:
statements
If else in for loop
 Example of if else in for loop:-
 for loop statement first iteration all the elements from 0 to 20
 Next the if statements checks the current number is even or not
 Check the condition is true the number is even run the if block and
otherwise number is odd run the else block .
If else in for loop
 Example of if else In for loop:-
for I in range(1,11):
if i%2==0:
print(“even number:-”,i)
else:
print(“odd number:-”,i)
else in for loop
 Python allows us to use the else statement with the for loop .
 Example of else statement of for loop.
for I in range(0,5):
print(i)
else:
print(“Done”)
For loop
 Fibonacci sequence:-
A,b=0,1
Print(“Fibonacci sequence:”)
For I in range(10):
print(a,end=“”)
c=a+b
a=b
b=a
While loop
 In python the while loop statement repeatedly executes a code block while
a particular condition is true.
 The python while loop allows a part of the code to be executed until the
condition return false.
 While loop is known as pre-tested loop.
 It can be viewed as a repeating if statement.
 Syntax of while loop
while expression:
statements
While loop
While loop
 The while statement checks the condition. The condition must return a
Boolean value like true and false.
 Next if the condition evaluates to true the while statement executes the
statements present inside its block.
 The while statement continues checking the condition in each iteration
and keeps executing its block until the condition becomes false.
While loop
 Example of while loop:-
i=1
While i<5:
print(i)
i=i+1
While loop
While loop with else statement:
num=int(input(“Enter the number bw 100 and 500”))
While num <100 or num > 500:
print(“incorrect num”, please enter correct number:-”)
num=int(input(“enter a number between be 100 and 500”))
else:
print(“given number is correct”, num)
While loop
 Example of while loop:-
i=1
num=0
number=int(input(“Enter the number:-”))
While i<=10:
print(“number,’x’,I,”=“,number*i)
i=i+1
Using else with while loop
 Python allows us to use the else statement with the while loop also. The
else block is executed when the condition given in the while statement
becomes false.
 Like for loop if the while loop is broken using break statement then the
else block will not be executed and the statement present after else block
will be executed.
 The else statement is optional to use with the while loop .
If else in while loop
 In python condition statements act depending on whether a given condition is
true or false.
 You can execute different block of codes depending on the outcome
condition.
 Thee if else statements always evaluate the true or false.
 We use the if else statement in the loop when condition iteration is needed if
the condition is true then the statement inside the if block will execute
otherwise the else block will execute.
 Syntax of if else statement:-
If condition:
statements
Else:
statements
If else with while loop
 Example of while loop in if else:-
N=int(input(“enter the number:-”)
While n>0:
if n % 2==0:
print(n, “is a even number”)
else:
print(n, “is a odd number”)
n-n-1
break statement while loop
 We can use the break statements inside a while loop using the same
approach.
 If condition to stop the while loop . If the current character is space then
the condition evaluates to true . Then the break statement will execute
and the loop will terminate.
 Else loop will continue to work until the main loop condition is true.
Break statement while loop
name=“Jessa29 Roy”
Size=len(name)
i=0
while I < size:
if name[i].isspace():
break
print(name[i],end=“”)
i=i+1
continue loop in while loop
 Example of continue statements:-
name=‘je sa a’
size=len(name)
i=-1
While I < size -1:
i=i+1
if name[i].isspace();
continue
print(name[i],end=“”)
LOOP CONTROL STATEMEMT IN FOR LOOP
 Loop control statement change the normal flow of execution.
 It is used when you want to exit a loop or skip a part of the loop based on
the given condition
 It is known as transfer statement
 Main three parts of transfer statement:-
 Break , continue and pass
Break statement for loop
 The break statement is used to terminate the loop. You can use the break
statement you want to stop the loop.
 You need to type the break inside the loop after the statement if you want
to break the loop.
 Break statement use to stop the loop execution
 This program for loop iterates over each number from a list.
 For example:-you are searching a specific email inside a file. You started
reading a file line by line using a loop. when you found an email yo can
stop the loop using break statement.
Break statement for loop
Flow chart of break statement:-
Break statement for loop
 Example of break statement:-
 We will iterate numbers from a list using a for loop and if we found a
number greater then 100 we will break the loop.
 Use the if condition to terminate the loop . If the condition evaluates to
true then the loop will terminate. Else loop will continue to work until the
main loop condition is true.
Break statement for loop
 Example of break statement:-
number=[10,20,30,40,50]
for i in number:
if i>40:
break
print(“current number”,i)
Break statement for loop
 Example of break statement:-
number=[1,4,7,8,15,20,35,45,55]
for i in number:
if I > 15:
break
else:
print(i)
Continue statement for loop
 The continue statement skips the current iteration of a loop and
immediately jumps to the next iteration.
 Use the continue statement when you want to jump to the next iteration of
the loop immediately.
 The interpreter found the continue statement inside the loop it skips the
remaining code and moves the next iteration.
 Example count the total number of ‘m’ in a string
 If statement checks the current character is m or not .if it is not m it
continues to the next iteration to check the following letter.
Continue statement for loop
 Example of continue statement:-
name=“marry man”
count=0
for char in name:
if char !=‘m’:
continue
else:
count=count+1
print(“total number of m is:-”,count)
Continue statement for loop
Example of continue statement:-
numbers=[2,3,11,7]
for I in numbers:
print(“current number is “,i)
if i > 10:
continue
square=i * I
print(“square of a current number is “, square)
Pass statement for loop
 The pass statement is null statement . nothing happens when the
statements
Is executed .it is used in empty functions or classes . when the interpreter
finds a pass statements in the program it returns no operation.
Syntax of pass statements:
for elements in sequence:
if condition:
pass
Pass statements for loop
 Example of pass statements:-
num=[1,4,5,3,7,8]
for I in num:
pass
------------------------------------------------------------------------------------------
-------------------------
months=[“January”,”june”,”march”,”april”]
for mon in months:
pass
prints(months)
Types of functions
 Types of functions:-
1. Built in function
2. User-defined Function
 Built in function:-The functions which are come along with python itself
are called a built in function or predefined function.
 Built in function are like:- range(), id() , type(), input() etc
 Example:-python range function generates the immutable sequence of
numbers starting from the given start integer to the stop integer.
Types of functions
 User-defined function:-
 Functions which are created by programmer according to the requirement
are called a user defined function.
 Example of simple create function:-
def sample():
x=10
print(x)
sample()
functions
functions
 Function definition
 Every function start with a “def” keyword.
 Every function should have a unique name.
 Every function name are not a same any keyword.
 User decide the parameters are given or not .
 User decide the arguments are given or not but parameters and arguments are
optional .
 But the parameters and arguments are given the user so user given the
parameters and arguments in parenthesis.
 Every function name with out arguments should end with a (:).
 Every function have return any value and return empty value.
 Multi value return can be done in (Tuple)
Functions calling
 Function calling:-
 So function calling is a simple process.
 So call the function as a function name so user create a function add and
user call the function is abc.
 Other wise interpreter show the error .
 So user call the function as a same name not use different name.
 User given the arguments name and end the program user call the
different arguments so this situation interpreter given the error.
 End of the part user define the function and call the function are same
name arguments and parameters include in the function are call the same
name.
functions
 Simple example of call function :-
def add(a,b): # define function and add parameters
sum=a+b #third variable add the value
return sum #use return statements
a=int(input(“enter 1st value:-”) #user input values
b=int(input(“enter 2nd value:-”) # user input values
c=add(a,b) #call function
Print(“the result is :-”,c) # print value
functions
 Simple example of calling function :-
def add(): #function define
a=10 #arguments and parameters
b=20 #arguments and parameters
c= a+b #use third variable and operation perform
print(c) # print the value
add() # function calling
Return statement
 The return statement is used to exit a function and go back to the place
from where it was called.
 It is called return statement.
 Syntax of return statement:-
return [expression_list]
 This statement can contain an expression that gets evaluated and the
values is returned .if there is no expression in the in the statement or the
return statement itself is not present inside a function then the function
will return the none object
Return statement
 Example of return statement in function:-
def sample(num):
if num>=0:
return num
else:
return –num
print((sample value(2))
print(sample value(-4))
Working function in python
Types of arguments in functions
Arguments of functions
1. Default arguments
2. Keyword arguments
3. Positional arguments
4. Arbitrary positional arguments
5. Arbitrary keyword arguments
functions
Default arguments
 Default arguments are values that are provided while defining function.
 The assignment operator = is used to assign a default value to the
arguments
 Default arguments become optional during the functional call
 If we provide a value to the default arguments during function call it
overrides the default value
 The function can have any number of default arguments
 Default arguments should follow non default arguments
Default arguments
 Example of default arguments:-
def sample(name,age=23):
print(“My name is:-”,name,”and age is :-,age)
sample(name=“sourav”)
_____________________________________________________________________
def hallo(name=“sourav”):
print(“hyy”, sourav)
hallo(“sunny”)
Message()
Default arguments
 Example of default argument:-
def sample(name,msg=“Good Morning”):
print(“hello”,name +’,’+msg)
sample(“sourav”)
sample(“sunny”,What are you doing”)
Keyword argument
 Functions can also be called using keyword arguments of the form
kwarg=value.
 During a function call value passed through arguments need not be in the
order of parameters in the function definition.
 The keyword arguments should match the parameters in the function
definition.
 A keyword argument is an argument value passed to function preceded by
the variable name and as equal sign.
Keyword argument
 Example of keyword arguments:-
def abc(name,surname):
print(“Hyy”,name,surname)
abc(name=“sourav”,surname=“Arora”)
abc=(surname=“kumar”,name=“sunny”)
Keyword arguments
 Example, of keyword arrguments:-
def food(**Kwargs):
print(Kwargs)
food(a=“Apple”)
food(fruits=“Mango”,vegitables=“Carrot”)
Scope of variable
 The scope of the variable depend upon the location where the variable is
being declared.the variable declared in open part of the program may not
be accessible to the other parts.
 In pyton the variable are defined with the two types of scope:-
1. Global variable
2. Local variable
 The variable defined outside any function is known to have a global scope
whereas the variable defined inside a function is known to have a local scope.
Local variable
.Example of local variable in function:-
def abc():
abc1=“hello I am going to delhi”
print(abc1)
abc()
print(abc1)
Global variable
 Example of global variable:-
def calculate(*args):
sum=0
for arg in args:
sum=sum+arg
print(“the sum is:-”,sum)
sum-=0
Calculate(10,20,30)
Print(“value of sum outside the function:-”,sum)
Positional arguments
 During a function call values passed through arguments should be in the
order af parameters in the function definition
 This is called positional arguments
 During a function call values passed through arguments should be in the
order of parameters in the function definition
 This is called positional arguments.
Positional arguments
 Example of positional arguments :-
def add(a,b,c):
return (a+b+c)
print(add(10,20,30))
print(add(10,c=30,b=20)
Required arguments
 Required arguments are the arguments passed to a function in correct
positional order.
 The number of arguments in the function call should match exactly with
the function definition
 To call the function printme(),you definititely need to pass one arguments
 The arguments is not provided in the function call or the position of the
arguments is changed the python interpreter will show the error
Required arguments
 Example of required arguments:-
def abc(name):
message=“Hi”+name
return message
name=input(“Enter the name:-”)
print(abc(name))
Required arguments
 Example of required arguments:-
def sample(p,t,r):
return(p*t*r)/100
P=float(input(“Enter the principle amount:-”))
r=float(input(“Enter the rate of interest:-”))
t=float(input(“Enter the time in years:-”))
print(“simple interest:-”,sample(p,r,t))
Arbitrary positional arguments
 Arbitrary positional arguments:-
For arbitrary positional arguments an asterisk(*) is placed before a parameter
in function definition which can hold non keyword variable length arguments
These arguments will be wrapped up in a tuple .
Before the variable number of arguments zero or more normal arguments
may occur.
Arbitrary positional arguments
 Example of arbitrary positional arguments:-
def add(*b):
result=0
for I in b:
result=result+I
return result
Print(add(10,20))
Arbitrary keyword arguments
 For arbitrary positional arguments a double asterisk(**) is placed before a
parameter in a function in a function which can hold keyword variable
length arguments.
 Example of arbitrary keyword arguments:-
def abc(**a):
for I in a.items():
print(i)
abc(number=5,colors=‘red’,fruits=“apple”)
recursion
 Python also accepts function recursion , which means a defined function
can call itself.
 Recursion is a common mathematical and programming concept.it means
that a function calls.
 The developer should be very careful with recursion as it can be quite easy
to slip into writing a function which never terminates or one that uses
excess amounts of memory or processor power.
 In python we know that a function can call other functions it is even
possible for the function to call itself.
 These types of construct are termed as recursion functions.
 The following image shows the working of a recursion function
recursion
 Syntax of recursion :-
def func():
|
| (recursive call)
|
func() ------
recursion
 Example of recursion of function:-
def factorial(x):
if x==1:
return 1
else:
return(x * factorial(x-1))
Num-3
Print(“the factorial of “,num, ‘is”,factorial(num))
Lambda function
 We use lambda functions when we require a nameless function for a short
period of time
 In python we generally use it as an arguments to a higher order function a
function that takes in other functions as arguments
 Lambda function as the anonymous function that is defined without a
name.
 Python allows us to not declare function in the standard manner by using
the def keyword.
 The anonymous function are declared by using thr lambda keyword
 Lambda functions are used along with built in function like filter() map()
Lambda function
 Syntax of lambda function:-
 Lambda arguments: expression
 Example of lambda function;-
X-lambda a:a+10
Print(x)
Print(“sum=“,x(20))
Lambda function
 Example of lambda function:-
def table(n):
return lambda a:a*n
n= int(input(“enter the number:-”))
b=table(n)
for I in range(1,11)
prnt(b(i)
Filter function
 The filter () function in python takes in a function and a list as a arguments.
 The function is called with all the items in the list and a new list is returned
which contains items for which the function evaluates to true.
 Example of filter () function,,
List=[1,5,4,6,8,11,3,12]
List1=newlit(filter(lambda x: (x%2 ==0),list)
Print(list1)
Map function
 The map() function in python takes in a function and a list
 The function is called with all the items in the list and a new list is returned
which contains items returned by that function for each item
 Python accepts a function and a list it gives a new list which contains all
modified items returned by the function for each item
Map function
 Example of map function:-
List=(10,20,30,40,50,60)
new_list=list(map(lambda x:x**2,list)
Print(new_list)
------------------------------------------------------
Exception handling
 Python has many built in exceptions that are raised when your program
eccounters an error .
 An exception is an event that occurs during the execution of programs that
disrupt the normal flow of execution.
 An exception is an event that occurs during the execution of programs that
disrupt the normal flow of execution.
 When a key is not found in a dictionary
 An exception is a python object that represents an error
 In python an exception is an object derives from the BaseExecption class
that contains information about an error event that occurred withon a
method .Exception Object Contains.
Exception handling
 Error type (Exception Name)
 The state of the program when the error occurred
 An error message describes the error event
 For example let us consider a program where we have a function A that
calls function B which in turn calls function C. if an exception occurs in
function C but is not handled in C the exception passes to B and then to A
 If never an error message is displayed and our program comes to a sudden
unexpected halt.
Exception handling
 Examples are the few standard exceptions:-
1. FileNotFoundExceptions
2. ImportError
3. RuntimeError
4. NameError
5. NameError
6. TypeError
Exception handling
 Why Use Exception:-
 Standardized error handling:-using built in exceptions or creating a custom
exceptions with a more precise name and description you can adequately
define the error event which helps you debug the error event.
 Cleaner code:- Exceptions separate the error-Handling code from regular
code which helps us to maintain large code easily.
 Robust Application:-with the help of exceptions we can develop a solid
application which can handle error event efficiently.
 Exceptions Propagation:-the exception propagates the call stack if you
don’t catch it.
Exception handling
 Example of Exception Handling:-
Exception handling
Exception handling
 The try and except Block to Handling Exceptions:-
 When an exceptions occurs python stops the program execution and
generates ab exception like error in the program like show error message
in python console.
 The doubtful code that may raise an exception an exception is called risky
code.
 Handle exceptions we need to use try and except block . risky code that
can raise an exception inside the try block and corresponding handling
code inside the except block.
Exception handling
 Syntax of exception handling:-
try:
statements in try block
except:
executed when exception occured in try block
Exception handling
Exception handling
 Example of try and except block:-
try:
a = 10
b = 0
c = a/b
print("The answer of a divide by b:", c)
except:
print("Can't divide with zero. Provide different number")
Exception handling
 Example of exception handling;-
try:
a = int(input("Enter value of a:"))
b = int(input("Enter value of b:"))
c = a/b print("The answer of a divide by b:", c)
except ValueError:
print("Entered value is wrong")
except ZeroDivisionError:
print("Can't divide by zero")
Exception handling
 Multiple Exceptions with a single except clause:-
 We can also handle multiple exceptions with a single except clause.
 For that we can use an tuple of values to specify exceptions in an except
clause.
Exception handling
 Example of multiple exceptions with a single except:-
try:
a =int(input(“Enter value of a:-”))
b =int(input(“Enter value of b:-”))
c=a/b
print(‘the answer of a divide by b:”,c)
except(ValueError, ZeroDivisionError):
print(“Enter valid value”)
Exception handling
 Using Try with Finally:-
1. Python provides the finally block which is used with the try block
statement.
2. The finally block is used to write a block of code that must execute
3. The try block raise an error or not.
4. Mainly finally block is used to release the external resource
5. The finally block provides a guarantee of execution.
Oops object oriented programming
 Python is a multi-paradigm programming language .it supports different programming
approaches.
 One of the popular approaches to solve a programming problem is by crating object
 This is known as object –oriented programming (oops)
 An object has two characterstics:
 Attributes
 Behaviour
 Like parrot is a object as it has some properties:
 Nme,age,color areattributes
 Singing ,dancing as behaviour
 The concept of oop in python focuses on crating reusable code.this concept is also
known as DRY(Don’t Try Yourself)
oops
 Major principles of object oriented programming :-
1. Class
2. Object
3. Method
4. Inheritance
5. Polymorphism
6. Data abstraction
7. encapsulation
oops
 Class:-
the class is a blueprint of objects . The class can be defined as a collection of
objects.
It is a logical entity that has some specific attributes and methods
For example if you have an employee class then it should contain an attributes and
methods like an email id , name , age , salary , etc
And class is a sketch of a program
They use the class keyword to declare any class
oops
 Syntax of class:-
class ClassName:
statements
|
|
|
statements-N
oops
oops
 Example of class :-
class employee():
def __init__(self,name,age,id,slary):
self.name=name
Self.age=age
self.id=id
self.salary=salary
emp1=employee(“sourav”,24,101,23900)
Print(emp1.__dict__)
oops
 Class and object example of oops:-
Class person:
def __init__(self,name,gender,profession):
self.name=name
self.gender=gender
self.profession=profession
def show(self):
print(“Name:-”,self,name,Gender:-”,self.gender,”,”Profession:-”,self.profession)
def work(self):
print(self.name,”working as a”, self.profession)
Obj=person(“Sourav”,”Male”,”Python Developer”)
Obj.show()
Obj.work()
oops
 Object:-
 A class is a collection of a object and it is a blueprint of program
 Objects are an instance of a class it is an entity that has state and
behaviour
 An object is essential to work with the class attributes. The object is
created using the class name.
 When we create an object of the class .the object is also called the instance
of a class
 A constructor is a special methods used to create and initialize an object of
a class
oops
 Example of object in class :-
Class person:
def __init__(salf,name,gender,profession):
self.name=name
self.gender=gender
self.profession=profession
def show(self):
print(“Name:-”,self,name,Gender:-”,self.gender,”,”Profession:-”,self.profession)
def work(self):
print(self.name,”working as a”, self.profession)
Obj=person(“Sourav”,”Male”,”Python Developer”)
Obj.show()
Obj.work()
oops
 Inheritance:-
 Types of inheritance:-
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
oops
 Single inheritance:-
 In single inheritance a child class inherits from a single parent class . Here
is a one child lass and one parent class.
Create one parent class called class One and child class called class
Two .
oops
 Example of single inheritance:
Class vehicle:
def vehicle_info(self):
print(“inside vehicle class”)
Class car(vehicle):
def car_info(self):
print(“inside car class):
Car=car()
Car.vehicle_info()
Car.car_info()
oops
 Multiple inheritance:-
In multiple inheritance one child class can inherit from multiple parent classes
so here is one child and multiple parent classes.
parent class parent class
child class
oops
 Example of multiple inheritance:-
Class person:
def person_info(self,name,age):
print(“name:”,name,”age:”,age)
Class company:
def company_info(self,company_name,location):
print('Name:', company_name, 'location:', location)
Class employee(person,company):
def employee_info(self,salary,skil):
print('Salary:', salary, 'Skill:', skill)
Emp=employee()
Emp.person_info(“sourav”,24)
Emp.company_info(“Ex-Tech”,”Mohali”)
Emp.employee_info(23900,”Python Developer)
oops
 Multiple inheritance:-
 In multiple inheritance a class inherits from a child class or derived class.
 Suppose three classes A,B,C,A is the superclass B is the child class of A , C
is the child class of B in other words we can say a chain of classes is classes
is called ,multiple inheritance
parent class
child class 1
child class 2
oops
 Example of multilevel inheritance:-
Class vehicle:
def vehicle_info(self):
print(“inside vehicle class”)
Class car(vehicle):
def car_info(self):
print(“inside car class):
Class sportscar(car):
def sports_car_info(self):
print(“inside sportscar class”)
Obj.car=suportscar()
Obj.car.car_info()
Obj.car.sports_car_info()
oops
 Hierarchical inheritance:-
In hierarchical inheritance more than one child class is derived from a single
parent class.
In other words we can say one parent class and multiple child classes.
parent class
Child class 1 child class 2 child class 3
oops
 Example of hierarchical inheritance:-
Class vehicle:
def info(self):
print(“this is vehicle”)
Class car(vehicle):
def car_info(self,na,e):
print(“car name is:”,name)
Class truck(vehicle):
def truck_info(self,name):
print(“truck name is:-”,name)
Obj1=car()
Obj1.info()
Obj.car_info(“BMW”)
Obj2=truck()
Obj2.info()
Obj.truck_info(“ford)
oops
 Hybrid inheritance:
When inheritance is consists of multiple types or a combination of different
inheritance is called hybrid inheritance.
parent class
child class1 child class2
child class3
oops
 Example of hybrid inheritance:-
Class vehicle:
def vehicle_info(self):
print(“inside vehicle class”)
Class car(vehicle):
def car_info(self):
print(“inside car class):
Class truck(vehicle):
def truck_info(self):
print(“inside truck class”)
Class sportcar(acr,vehicle):
def sport_car_info(self):
print(“inside sportcar class”)
Obj=sportcar()
Obj.vehicle_info()
Obj.car_info()
Obj.sport_car_info()
oops
 Polymorphism in python is the ability of an object to take many forms.
 In simple words polymorphism allows us to perform the same action in
many different ways.
 For example jessa acts as an employee when she is at the office. However
when she is at home she acts like a wife also she represents herself
differently in different places.
 Therefor the same person takes different forms as per the situation
oops
oops
 Polymorphism in built in function len()
 The built in function len() calculate the length of an object depending
upon its type if an object is a string it returns the count of characters and
if an objects is a list it returns the count of items in a llist.
 The len () method treats on objects as per its class type
 Example of len () function
students=[“harry”,”garry”,”sharry”]
School “abc school”
Print(len(studnets))
Print(len(school))Śś
oops
Polymorphism with inheritance
 Polymorphism is mainly used with inheritance .
 In inheritance child class inherits the attributes and methods of a parent
class
 The existing class is called a base class or parent class and the new class is
called a subclass or child class or derived class
 Using method overloading polymorphism allows us to define methods in
the child class that have the same name as the methods in the parent class
the process of re-implementing the inherited method in the child class is
known as method overloading.
Method overloading
 We have a vehicle class as a parent and a car and truck as its sub class
 But each vehicle can have a different seating capacity speed etc
 So we can have the same instance method name in each class but with a
different implementation
 This code can be extended and easily maintained over time
Method overloading
Method overloading
 Example of method overloading:-
Class vehicle:
def __init__(self,name,color,price):
self.name=name
self.color=color
self.price=price
def sjow(self):
print(“details;-”,self.name,self.color,self.price)
def max_speed(self):
print(“vehicle max speed is 150”)
def change_gear(self):
print(“vehicle change 6 gear”)
Class car(vehicle):
def max_speed(self):
print(“car max speed is 300”)
deef change_gear(self):
print(“carchange & gear”)
car=car(“car x1”,”red”,305000)
Car.show()
Car.max_speed()
Car.change_gear()
Vvehicle=vehicle(truck x1”, “white”, 758000)
Vehicle.show()
Vehicle.max_speed()
Vehicle.change_gear()

More Related Content

What's hot (20)

PPTX
Python Data Structures and Algorithms.pptx
ShreyasLawand
 
PPTX
File handling in Python
Megha V
 
PPTX
Operators in Python
Anusuya123
 
PDF
Python Flow Control
Mohammed Sikander
 
PDF
Object oriented approach in python programming
Srinivas Narasegouda
 
PDF
Python exception handling
Mohammed Sikander
 
PPTX
Python Functions
Mohammed Sikander
 
PPTX
Basic data types in python
sunilchute1
 
PPTX
Python Data-Types
Akhil Kaushik
 
PPTX
Python Scipy Numpy
Girish Khanzode
 
PPTX
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
PDF
Datatypes in python
eShikshak
 
PPTX
Operators in java
Then Murugeshwari
 
PDF
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
PDF
Python list
Mohammed Sikander
 
PPTX
Oop c++class(final).ppt
Alok Kumar
 
PPT
Python Programming ppt
ismailmrribi
 
PPTX
Modules in Python Programming
sambitmandal
 
PPTX
Data types in java
HarshitaAshwani
 
PPTX
Pointers in c++
Vineeta Garg
 
Python Data Structures and Algorithms.pptx
ShreyasLawand
 
File handling in Python
Megha V
 
Operators in Python
Anusuya123
 
Python Flow Control
Mohammed Sikander
 
Object oriented approach in python programming
Srinivas Narasegouda
 
Python exception handling
Mohammed Sikander
 
Python Functions
Mohammed Sikander
 
Basic data types in python
sunilchute1
 
Python Data-Types
Akhil Kaushik
 
Python Scipy Numpy
Girish Khanzode
 
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Datatypes in python
eShikshak
 
Operators in java
Then Murugeshwari
 
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Python list
Mohammed Sikander
 
Oop c++class(final).ppt
Alok Kumar
 
Python Programming ppt
ismailmrribi
 
Modules in Python Programming
sambitmandal
 
Data types in java
HarshitaAshwani
 
Pointers in c++
Vineeta Garg
 

Similar to Python variables and data types.pptx (20)

PPTX
2. Values and Data types in Python.pptx
deivanayagamramachan
 
PDF
Datatypes in Python.pdf
king931283
 
PPTX
1-Introduction to Python, features of python, history of python(1).pptx
MAHESWARIS55
 
PDF
23UCACC11 Python Programming (MTNC) (BCA)
ssuser7f90ae
 
PPTX
Values and Data types in python
Jothi Thilaga P
 
PDF
CS-XII Python Fundamentals.pdf
Ida Lumintu
 
PDF
4. Data Handling computer shcience pdf s
TonyTech2
 
DOCX
unit 1.docx
ssuser2e84e4
 
PDF
The python fundamental introduction part 1
DeoDuaNaoHet
 
PPT
Python - Module 1.ppt
jaba kumar
 
PDF
E-Notes_3720_Content_Document_20250107032323PM.pdf
aayushihirpara297
 
PPTX
IOT notes,................................
taetaebts431
 
PPTX
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
PDF
Programming in Civil Engineering_UNIT 2_NOTES
Rushikesh Kolhe
 
PPTX
Python PPT2
Selvakanmani S
 
PPTX
2. Getting Started with Python second lesson .pptx
Primary2Primary2
 
PPTX
Python basics
Manisha Gholve
 
PPTX
009 Data Handling .pptx
ssuser6c66f3
 
PPTX
Presentation on python data type
swati kushwaha
 
PPTX
1691912901477_Python_Basics and list,tuple,string.pptx
KUSHSHARMA630049
 
2. Values and Data types in Python.pptx
deivanayagamramachan
 
Datatypes in Python.pdf
king931283
 
1-Introduction to Python, features of python, history of python(1).pptx
MAHESWARIS55
 
23UCACC11 Python Programming (MTNC) (BCA)
ssuser7f90ae
 
Values and Data types in python
Jothi Thilaga P
 
CS-XII Python Fundamentals.pdf
Ida Lumintu
 
4. Data Handling computer shcience pdf s
TonyTech2
 
unit 1.docx
ssuser2e84e4
 
The python fundamental introduction part 1
DeoDuaNaoHet
 
Python - Module 1.ppt
jaba kumar
 
E-Notes_3720_Content_Document_20250107032323PM.pdf
aayushihirpara297
 
IOT notes,................................
taetaebts431
 
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
Programming in Civil Engineering_UNIT 2_NOTES
Rushikesh Kolhe
 
Python PPT2
Selvakanmani S
 
2. Getting Started with Python second lesson .pptx
Primary2Primary2
 
Python basics
Manisha Gholve
 
009 Data Handling .pptx
ssuser6c66f3
 
Presentation on python data type
swati kushwaha
 
1691912901477_Python_Basics and list,tuple,string.pptx
KUSHSHARMA630049
 
Ad

Recently uploaded (20)

PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PDF
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
Hashing Introduction , hash functions and techniques
sailajam21
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Day2 B2 Best.pptx
helenjenefa1
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
Ad

Python variables and data types.pptx

  • 1. Python variables and data types INTRODUCTION OF PYTHON VARIABLES… • VARIABLE IS A NAME THAT IS USED TO REFER TO THE MEMORY LOCATION • PYTHON VARIABLE IS ALSO KNOWN AS IDENTIFIER TO USED TO HOLD THE VALUE • PYTHON VARIABLE NAMES CAN BE GROUP OF BOTH OF LETTER AND DIGITS • USE LOWER CASE LETTER AND UPPER CASE LETTER ARE DIFFERENT LIKE RAHUL AND RAHUL • THEY USE THE UNDERSCORE THE VARIABLE LIKE (_A) & (A_)
  • 2. Python variables Variable naming rules Declaring variables Multiple Assignment Deleting variables Python Variable Types
  • 3. Variable naming rules  The first character of variable must be an alphabet or underscore(_)  All the character except the first character may be an alphabet of lower case like(a-z),upper case like(A-Z) and they use the digits(0-9)  Identifier name must not use any white space and special character (!,@,#,%)  Identifier name must not be similar any keyword  Identifier name are case sensitive for example :- NAME and name are the different name not a same variable  Example of valid identifier name is :- _a,a123 etc
  • 4. declaring variables  Python does not bind us to declare a variable before using the validation  It allow to create a variable at the required time  We don’t need to declare explicitly variable  We assign any value to the variable that variable declared  The equal (=) operator is used to assign the value of variable  Example :- A=10 A is a variable name and (=) use the assign the value and 10 is a value of A
  • 5. Python variables  Example of python variable:- First Declare variable Second add next variable Finally print the variable values A=10 B=10 C=A+B Print(c)
  • 7. Multiple Assignment  Python allows us to assign a value to multiple variable in a single statement It is known as Multiple Assignment  We can apply multiple assignment in two ways  Either by assigning a single value to multiple variables or assigning a multiple value in multiple variables
  • 8. Assigning single value to multiple variables  Example:- a=b=c=100 print(a) print(b) print(c) User assign the multiple variable and assign the single value to multiple variable Like a and b and c variables value is 100 And next step is print the all values
  • 9. Assigning multiple values to multiple variables  Example:- a,b,c=10,20,30 print(a) print(b) print(c) User assign the multiple variable and assign the multiple value And second step print the all values
  • 10. Deleting variables  We can delete the variable use Del keyword syntax:- del<variable_name> Example :- x=5 print(x) del x print(x) I print the variable x and assign the value and print the value after printing the value Delete the variable x
  • 11. Python variable types They are the two types of variables in python First one is Local Variable Second one is Global variable
  • 12. Local variable  The local variable is create under the function not define the outside of the function .It is known as local variable and local scope Local Variable Example :- def sample(): y=“local” print(y) sample()
  • 13. Global variable  In python variable declare outside of the function in global scope is known as global variable .  This means that a global variable can accessed inside or outside of the function Example of Global Variable :- x=“global” def sample(): print(“x inside :-” ,x) sample() print(“x outside:-”,x)
  • 14. Python data types  Variable can hold value and every value has a data type  We do not need the define the type of the variable while declaring Example:- a=5  The variable a hold the integer value five  User can not define any Data Type  Python interpreter will automatically variable a given integer Data Type  Python provide the type () function to check the data type any variable
  • 15. Python data types EXAMPLE OF CHECK THE DIFFERENT DATA TYPES:- a=10 b=“Hi python” c=10.5 Print(type(a)) Print(type(b)) Print(type(c))
  • 17. Python data types chart  Python provides Various type of Data Types 1. Numbers 2. Sequence type 3. Boolean 4. Set 5. Dictionary
  • 18. Number data type  Number data type can store number values  Integer float and complex value belong to number data type  Python provide the type () function to check the any type of data type variable  Number Data Type divide into sum parts :- 1. Integer 2. Float 3. complex
  • 19. Number data type  Example of number data type like integer float and complex :- a=5 print(“The type of a”, type(a)) b=40.5 print(“The type of b”, type(b)) c=1+3j print(“The type of c”, type(c)) print(“c is a complex number “, is instance(1+3j,complex))
  • 20. Definition of int float and complex data type 1) INT:-integer value is the value of number value like 10,20,30,40,50,5,4,3,2,1 python has no restriction on the length of an integer value Example :- a=10 (a)<-- is a variable and user give the a variable value is 10 10 is a integer value .python by default check the data type 2) Float:- float data type store the value in floating-point number like 1.9,20.5,9.9902 it is accurate 15 decimal points Example:- a=5.9 (a)<-- is a variable and user give the a variable value is 5.9 5.9 is a Float value .python by default check the data type 3) complex:-A complex number contains an ordered pair . complex number are written in the form x + yj, where x is a real part and y is a imaginary part Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part
  • 21. Sequence type  Sequence types divided into three parts I. String II. List III. tuple  String:- The string can be defined as the sequence of characters python use single ,double and triple quotes to define a string. string is a sequence of unique characters string handling in python the operator + is used to concatenate the two strings.
  • 22. Sequence type Example:- “hello”+”python” returns hellopython Example of string:- str=“hello python“ print(str) s=‘’’multiline string’’’ print(s)
  • 23. Sequence type Example of string:- str1=“hello javatpoint” str2=“how are you” print(str1[0:2]) print(str1[4]) print(str2[1*2]) print(str1+str2)
  • 24. Sequence type  List:- python list are similar to array in c .list can contain data of different types .the items are stored in the list are separated with the comma (,) and enclosed with the square brackets[].  List:-list are use slice operator to access the data of the list. The concatenation operator (+) and repetition operator(*) works with the same way as they working with the string.  List:- list contain all type of data types like int,float,string.  List:-list are allowed duplicates elements.  List:- list are mutable the user can modify elements are list.  List:-list are start with [] square brackets.
  • 25. Sequence type  Example of list:- list=[1,”hii”,python”,98765] print(type(list)) print(list) print(list[3:]) print(list[0:2]) print(list+list) print(list*3)
  • 26. Sequence type Example of list:- list = ["Jessa", "Kelly", 20, 35.75] print(list) print(type(list)) print(list[0]) print(list[1:5]) list[1] = "Emma" print(list[1]) list2 = list(["Jessa", "Kelly", 20, 35.75]) print(list2)
  • 27. Sequence type  tuple data type:-A tuple is a similar to the list .list and tuple can contain the collection of different data types .the items of the tuple are separated with the comma(,) and enclosed with the parentheses().  tuple data type:- Tuple are read only data . We can not modify any element into the tuple .  tuple data type:- Tuple are ordered collection of data .  tuple data type:- Tuple are unchangeable Example :- if you want to store the roll no of students that you don’t change so you can use the Tuple data type
  • 28. Sequence type Example of Tuple Data type:- my_tuple = (11, 24, 56, 88, 78) print(my_tuple) print(type(my_tuple)) print(my_tuple[2]) print(my_tuple[2:7]) my_tuple2 = tuple((10, 20, 30, 40)) print(my_tuple2)
  • 29. Sequence type Example of Tuple Data type:- Reverse tuple;- Tuple=(11,22,33,44,55,66,77) Print(tuple[::-1]
  • 30. dictionary  Dictionary:-dictionary is an unordered set of key –value pair of items .key can hold primitive data type and value is a arbitrary project.  Dictionary:-dictionary are separated with the comma(,) as enclosed with the curly braces {}  Dictionary:- the dictionary type is represented using a Dict class .if you want to store the name and roll no all students then you can use the Dict type  Dictionary:-dictionary are duplicate keys are not allowed but the value can be duplicate key the old value will be replaced with the new value  Dictionary:- dictionary is a mutable which means we can modify the items  Dictionary:- dictionary is unordered so we can’t perform indexing and slicing
  • 31. dictionary  Dictionary;-  abc={1:”sourav”,2:”sham”,3:”sunny”} print(abc) print(“1st name is “+abc[1]) print(“2nd name is “+abc[2]) print(abc.keys()) print(abc.values())
  • 32. boolean  Boolean:- Boolean type provides two built-in values, True and False. These values are used to determine the given statement true or false.  Boolean:-It denotes by the class bool. True can be represented by any non- zero value or 'T' whereas false can be represented by the 0 or 'F'. Exampleof booleAN:- Print(type(true)) Print(type(false)) Print(false)
  • 33. set  set :- python set is the unordered collection of the data type.it is iterable , mutable(cannot modify after creation), and has unique elements.  Set:- In set, the order of the elements is undefined; it may return the changed sequence of the element.  set;-The set is created by using a built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma.
  • 34. set  The set data type has the following characteristics. 1. It is mutable which means we can change set items 2. Duplicate elements are not allowed 3. Heterogeneous (values of all data types) elements are allowed 4. Insertion order of elements is not preserved, so we can’t perform indexing on a Set
  • 36. set  Exampleof set:- my_set = {100, 25.75, "Jessa"} print(my_set) print(type(my_set)) my_set.add(300) print(my_set) my_set.remove(100) print(my_set)
  • 37. keywords  Python keywords are special reserved words that convey a special meaning to the compiler/interpreter .  Each Keywords has a special meaning and a specific operation .  These keywords can’t be used as a variable .  Following is the list of python keywords.
  • 39. keywords  Consider the following explanation of keywords. 1. True - It represents the Boolean true, if the given condition is true, then it returns "True". Non-zero values are treated as true. 2. False - It represents the Boolean false; if the given condition is false, then it returns "False". Zero value is treated as false 3. None - It denotes the null value or void. An empty list or Zero can't be treated as None. 4. and - It is a logical operator. It is used to check the multiple conditions. It returns true if both conditions are true. Consider the following truth table. 5. or - It is a logical operator in Python. It returns true if one of the conditions is true 6. not - It is a logical operator and inverts the truth value.
  • 40. keywords  A B A and B True True True True False True False True True False False False
  • 42. keywords  7. assert - This keyword is used as the debugging tool in Python. It checks the correctness of the code. It raises an AssertionError if found any error in the code and also prints the message with an error.  Example of assert:- a=10 b=20 c=a+b Print(“The value is :-”,d)
  • 43. keywords  8. Def :-The Def keyword is used to declare the function in python . They use the Def keyword. Example of Def keyword :- def sample(): a=10 print(“The value is :-”,a) sample()
  • 44. keywords  9. Class:- It is used to represent the class in python. The class is the blueprint of the objects. It is the collection of the variable and methods Example of the class :- class parent: variables………….. def sample(): statements…….
  • 45. keywords  10. Continue:- The continue statement are used to stop the execution of the current iteration. Following example of continue statement:- a=0 while a<4 a+=1 if a==2: continue print(a)
  • 46. keywords  11.Break:- The break statement are used to terminate the loop execution and control transfer to end of the loop . Example of break statement:- for i in range(5): if( i==3): break print(i) print(“End of execution”)
  • 47. keywords  12. If Statement:- If statement is represent the conditional statement. The execution of a particular block is decided by if statement .  Example of If Statement:- i=18 if(i<12): print(“I am less than 18”)
  • 48. keywords  13. Else:-The else statement is used with the if statement .when if statement returns false then else block are executed. Example of Else statement:- n=11 if (n%2==0): print(“Even”) else: print(“odd”)
  • 49. keywords  14. Elif:- The Elif keyword is used to check the multiple conditions . it is short for else-if . If the previous condition is false , then check until the true condition is found . Example of Elif statement:- marks = int(input("Enter the marks:")) if(marks>=90): print("Excellent") elif(marks<90 and marks>=75): print("Very Good") elif(marks<75 and marks>=60): print("Good") else: print("Average")
  • 50. Python Operators  The operator can be defined as a symbol which is responsible for a particular operation between two operands.  Operators are the pillars of a program on which the logic is built in a specific programming language  Example of python Operators:-
  • 51. Operators 1. Arithmetic operators 2. Comparison operators 3. Assignment Operators 4. Logical Operators 5. Bitwise Operators 6. Membership Operators 7. Identity Operators
  • 52. Arithmetic Operators  Arithmetic operators are used to perform arithmetic operations between two operands.  It includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent (**) operators.  Example of Arithmetic operators:-  A=20  B=10  C=a+b,a-b,a*b,a%b,a/b,a//b,a**b  Print(c)
  • 54. Comparison operator  The name itself is explaining that this operator is used to compare different things or values with one another.  In Python, the Comparison operator is used to analyze either side of the values and decides the relation between them.  Comparison operator is also termed as a relational operator because it explains the connection between them.  Example of comparison operators:-  A=20  B=10  C=a==b,a!=b,a>b,a<b,a>=b,a<=b  Print(c)
  • 55. Comparison operator  Comparison operators are used to comparing the value of the two operands and returns Boolean true or false accordingly.
  • 56. Assignment Operators  The assignment operators are used to assign the value of the right expression to the left operand.
  • 58. Assignment Operators a=4 a/=2 Print(a) a=4 a **= 2 Print(a) a=5 a %=2 Print(a) a=4 a //=2 Print(a)
  • 59. Bitwise Operators  The bitwise operators perform bit by bit operation on the values of the two operands.
  • 60. Bitwise Operators It performs logical AND operation on the integer value after converting an integer to a binary value and gives the result as a decimal value it returns true only if both operands are true otherwise it returns false Example of Bitwise AND operators:- a=7 b=4 c=5 Print(a&b) Print(a&c) Print(b&c)
  • 61. Bitwise Operators  Bitwise or operators:- It performs logical OR operation on the integer value after converting integer value to binary value and gives the result a decimal value . It returns false only if both operands are true otherwise it returns true. Example of Bitwise OR operators:- a=7 b=4 c=5 Print(a | b) Print(a | c) Print(b| c)
  • 62. Bitwise Operators  Bitwise XOR operators:- It performs logical XOR operation on the binary value of a integer and gives the result as a decimal value. Example of a Bitwise XOR operators:- a=7 b=4 c=5 Print( a ^ c) Print(b ^ c)
  • 63. Bitwise Operators  Bitwise 1’s complement ~:-  It performs 1’s complements operation it invert each bit of binary value and returns the bitwise negation of a value as a result. Example of Bitwise 1’st complements:- a=7 b=4 c=3 Print(~a, ~b, ~c)
  • 64. Bitwise Operators  Bitwise left-shift << operators:- The left-shift << operators performs a shifting bit of a value by a given number of the place and fills 0’s to new positions. Example of Bitwise left-shift << operators:- print(4 << 2) print(5 << 3)
  • 65. Bitwise Operators  Bitwise right-shift >> The left-shift >> operator performs sifting a bit of value to the right by a given Number of places. Example of Bitwise right-shift >> operators:- print(4 >> 2) print(5 >> 2)
  • 66. Membership operators  Membership operators:- python membership operators are used to check for membership of objects in sequence ,  such as string , list , tuple. It checks whether the given value or variable is present in a given sequence.  If present it will return true else false.  Python there are two membership operators IN and NOT IN
  • 67. Membership operators  IN operator:- it returns a result as true. If it finds a given object in the sequence. Otherwise it return false.  Example of IN OPERATORS:- list[11,15,21,29,50,70] num=15 If num in list: print(“number in present”) else: print(“number not in present”)
  • 68. Membership operators  NOT IN OPERATOR:-it returns true if the object is not present in a given sequence.  Otherwise it return false.  Example of NOT In OPERATOR:- TUPLE(11,15,21,29,50,70) num=15 If num not in tuple: print(“number is present”) else: print(“number is not present”)
  • 69. IDENTITY OPERATORS  Identity operators check whether the value of two variable is the same or not.  This operator is known as reference - quality operators.  Because the identity operators compares value according to two variable memory addresses  Python has 2 identity operators is and is not
  • 70. IDENTITY OPERATORS  IS OPERATOR:- this operator return Boolean true or false.  It return true if the memory address first value is equal to the second value otherwise it return false.  Example of is operators:- X=10 Y=11 Z=10 Print(x is y) Print(x is z)
  • 71. IDENTITY OPERATORS  IS NOT OPERATORS: the is not operators return Boolean value either true or false.  It return true if the first value is not equal to the second value  Otherwise it return false. Example of is not operator: X=10 Y=11 Z=10 Print(x is not y) Print(x is not z)
  • 72. Control flow statements  The control flow statements are divided into three parts:- 1. Conditional statements 2. Iterative statements 3. Transfer statements
  • 74. Control flow statements  Conditional statement:-  The conditional statement are depending on whether a given condition is true or false.  You are execute different blocks of codes depending on the outcome of a condition.  Condition statements always evaluate to either true or false  Types of conditional statements:- 1. if statements 2. If-else 3. If-elif-else 4. Nested if-else
  • 75. Control flow statements  Iterative statements:- iterative statement allow us to execute a block of code repeatedly as long as the condition is true.  We also call it a loop statements  Python provides us to the following two loop statement to perform Types of a iterative statements:- 1. For loop 2. While loop
  • 76. Control flow statements  Transfer statement:- in python transfer statement are used to alter(stop) the program way of execution.  The types of transfer statement:- 1. Break statement 2. Continue statement 3. Pass statement
  • 77. Conditional statement  If statement in python:- In control statement the if statement is the simplest form.it takes a condition and evaluate to either True or False If the condition is true then the true block of code will be executed and if condition is false then the block of code is skipped and controller moves the next block of code like else block. Syntax of if statement:- If condition: statement 1 statement 2 statement n
  • 78. Conditional statement  Flow chart of if else statement:-
  • 79. If else statement  Example of if else statement:- num=5 if num >=0: print(“number is positive”) else: print(“number is negative”)
  • 80. If else statement  Example of if else statement:- Password=input(“Enter password:-) If password==“Hello@5656”: print(“correct password”) else: print(“invalid password”)
  • 81. If-elif-else  Flow chart of if elif else:-
  • 82. If-elif-else  If-elif-else codition statement has an elif blocks to chain multiple conditions one after another.  This is useful when you need to check multiple coditions.  The if –elif-else we can make a tricky decision.  The elif statement checks multiple conditions one by one and if the condition fulfllls then execute the code.
  • 83. If-elif-else  Syntax of if elif else statement:- If condition-1: statement 1 elif condition-2: statements2 elif condition-3: statement 3 else: statements
  • 84. If-elif-else Example of if leif else statement:- num=3 If num >0: print(“positive”) elif num==0: print(“zero”) else: print(“negative number”)
  • 85. If-elif-else  Example of if elif else statement:- a=40 b=30 If b>a: print(“b is greater then a”) elif a==b: print(“a and b are equal”) else: print(“a is greater then b”)
  • 86. If –elif-else  Example of if elif and else statement:- a=50 If(a==20): print(“value of a is 20”) elif(a==30): print(value of a is 30”) elif (a==40) print(“value of a is 40”) else: print(“value of a is greater then 40”)
  • 87. Nested if else statement  Nested if else statement:-in python nested if else statement is an if statement inside the if else statement  It is allowed in python to put any number of if statement in another if statement.  Indentation is the only way to different level nesting.  We can have a if …elif …else statement inside another if elif ..else statement this is called nesting in computer.  Any number of these statement can be nested inside one another
  • 88. Nested if else statement  Flow chart of Nested if else statement:-
  • 89. Nested if else statement  Syntax of the nested-if else: If condition outside: if condition inside: statement of inside if else: statement of inside else: statement of outside if else: outside else Statement outside if block
  • 90. Nested if else statement  Example of nested if else statement:- a=int(input(“Enter 1st value:-”) b=int(input(“Enter 2st value:-”) If a>=b: if a == b: print(a ‘and’, b, ‘are equal’) else: print(a, ‘is greater then’, b) else: Print(a, ‘is smaller then’,b)
  • 91. Nested if else statement  Example of nested if else statement:- num=int(input(“Enter a number:-”)) if num >=0: print(“zero”) else: print(“positive number”) else: print(“negative number”)
  • 92. For loops  A for loop is used for iterating over a sequence that is either a list a tuple a dictionary a set or a string.  This is less like the for keyword in other programming language and work more like an iterator method.  For loop we can execute a set of statement once for each item in a list tuple set etc.  Syntax if for loop:-  For iterating_var in sequence: statement(s)
  • 93. For loops  Syntax of for loop:- for I in range: statement 1 statement 2 statement n Syntax of for loop I in the iterating variable and the range specific how many times the loop should run. For example if a list contains 10 number the for loop will execute 10 times to print each number. Iteration of the loop the variable I get the current value.
  • 94. For loops  Flow chart of for loop:-
  • 95. For loop with range()
  • 96. For loop with range function  The range function is used to generate the sequence of the numbers. If we pass the range like (10) it will generate the sequence of the numbers from 0 to 9  The syntax of the range function:- Range(start , stop , step size) Range(1,10,2)  The start represents the beginning of the iteration.  The stop represents that the loop will iterate till stop n-1 the range (1,10) will generate numbers 1 to 9 iteration  The step size is used to skip the specific numbers from the iteration it is optional to use.by default the step size is 1 .
  • 97. For loop with range function  Example of range function of for loop:-  for I in range(10): print(I,end=“”)  For I in range(1,10): print(I,end=“”)  For I in range(1,10,2): print(I,end=“”)
  • 98. For loop with range function  Example of range function in for loop:- a=int(input(“Enter any number:-”) for i in range(1,11) c=a*I print(a,”X”,I”=“c)
  • 99. Nested for loop in python  Python allows us to nest any number of for loops inside a for loop . the inner loop is executed n number of times for every iteration of the outer loop  Syntax of nested for loop for I in range: #outer loop for j in range : # inner loop #statements statements
  • 100. Nested for loop in python  Example of nested for loop:- for I in range(0,6): for j in range(i): print(“*”,end=“ “) print()
  • 101. Nested for loop in python  Example of nested for loop:- for I in range(1,6): for j in range(i): print(i,end=“”) print()
  • 102. If else in for loop  If else statement use in for loop.  If else is a conditional statement for example print student names who got more then 80 percent.  If else statement check the condition and if the condition is true it execute the block of code present inside the if block and if the condition is false it will execute the block of code present inside the else block.  If else condition is used inside the loop the interpreter check the if condition in each iteration and the true condition is run and false condition is skkiped.
  • 103. If else in for loop  Syntax of if else statement in for loop:- for i in range(--): if condition: statements else: statements
  • 104. If else in for loop  Example of if else in for loop:-  for loop statement first iteration all the elements from 0 to 20  Next the if statements checks the current number is even or not  Check the condition is true the number is even run the if block and otherwise number is odd run the else block .
  • 105. If else in for loop  Example of if else In for loop:- for I in range(1,11): if i%2==0: print(“even number:-”,i) else: print(“odd number:-”,i)
  • 106. else in for loop  Python allows us to use the else statement with the for loop .  Example of else statement of for loop. for I in range(0,5): print(i) else: print(“Done”)
  • 107. For loop  Fibonacci sequence:- A,b=0,1 Print(“Fibonacci sequence:”) For I in range(10): print(a,end=“”) c=a+b a=b b=a
  • 108. While loop  In python the while loop statement repeatedly executes a code block while a particular condition is true.  The python while loop allows a part of the code to be executed until the condition return false.  While loop is known as pre-tested loop.  It can be viewed as a repeating if statement.  Syntax of while loop while expression: statements
  • 110. While loop  The while statement checks the condition. The condition must return a Boolean value like true and false.  Next if the condition evaluates to true the while statement executes the statements present inside its block.  The while statement continues checking the condition in each iteration and keeps executing its block until the condition becomes false.
  • 111. While loop  Example of while loop:- i=1 While i<5: print(i) i=i+1
  • 112. While loop While loop with else statement: num=int(input(“Enter the number bw 100 and 500”)) While num <100 or num > 500: print(“incorrect num”, please enter correct number:-”) num=int(input(“enter a number between be 100 and 500”)) else: print(“given number is correct”, num)
  • 113. While loop  Example of while loop:- i=1 num=0 number=int(input(“Enter the number:-”)) While i<=10: print(“number,’x’,I,”=“,number*i) i=i+1
  • 114. Using else with while loop  Python allows us to use the else statement with the while loop also. The else block is executed when the condition given in the while statement becomes false.  Like for loop if the while loop is broken using break statement then the else block will not be executed and the statement present after else block will be executed.  The else statement is optional to use with the while loop .
  • 115. If else in while loop  In python condition statements act depending on whether a given condition is true or false.  You can execute different block of codes depending on the outcome condition.  Thee if else statements always evaluate the true or false.  We use the if else statement in the loop when condition iteration is needed if the condition is true then the statement inside the if block will execute otherwise the else block will execute.  Syntax of if else statement:- If condition: statements Else: statements
  • 116. If else with while loop  Example of while loop in if else:- N=int(input(“enter the number:-”) While n>0: if n % 2==0: print(n, “is a even number”) else: print(n, “is a odd number”) n-n-1
  • 117. break statement while loop  We can use the break statements inside a while loop using the same approach.  If condition to stop the while loop . If the current character is space then the condition evaluates to true . Then the break statement will execute and the loop will terminate.  Else loop will continue to work until the main loop condition is true.
  • 118. Break statement while loop name=“Jessa29 Roy” Size=len(name) i=0 while I < size: if name[i].isspace(): break print(name[i],end=“”) i=i+1
  • 119. continue loop in while loop  Example of continue statements:- name=‘je sa a’ size=len(name) i=-1 While I < size -1: i=i+1 if name[i].isspace(); continue print(name[i],end=“”)
  • 120. LOOP CONTROL STATEMEMT IN FOR LOOP  Loop control statement change the normal flow of execution.  It is used when you want to exit a loop or skip a part of the loop based on the given condition  It is known as transfer statement  Main three parts of transfer statement:-  Break , continue and pass
  • 121. Break statement for loop  The break statement is used to terminate the loop. You can use the break statement you want to stop the loop.  You need to type the break inside the loop after the statement if you want to break the loop.  Break statement use to stop the loop execution  This program for loop iterates over each number from a list.  For example:-you are searching a specific email inside a file. You started reading a file line by line using a loop. when you found an email yo can stop the loop using break statement.
  • 122. Break statement for loop Flow chart of break statement:-
  • 123. Break statement for loop  Example of break statement:-  We will iterate numbers from a list using a for loop and if we found a number greater then 100 we will break the loop.  Use the if condition to terminate the loop . If the condition evaluates to true then the loop will terminate. Else loop will continue to work until the main loop condition is true.
  • 124. Break statement for loop  Example of break statement:- number=[10,20,30,40,50] for i in number: if i>40: break print(“current number”,i)
  • 125. Break statement for loop  Example of break statement:- number=[1,4,7,8,15,20,35,45,55] for i in number: if I > 15: break else: print(i)
  • 126. Continue statement for loop  The continue statement skips the current iteration of a loop and immediately jumps to the next iteration.  Use the continue statement when you want to jump to the next iteration of the loop immediately.  The interpreter found the continue statement inside the loop it skips the remaining code and moves the next iteration.  Example count the total number of ‘m’ in a string  If statement checks the current character is m or not .if it is not m it continues to the next iteration to check the following letter.
  • 127. Continue statement for loop  Example of continue statement:- name=“marry man” count=0 for char in name: if char !=‘m’: continue else: count=count+1 print(“total number of m is:-”,count)
  • 128. Continue statement for loop Example of continue statement:- numbers=[2,3,11,7] for I in numbers: print(“current number is “,i) if i > 10: continue square=i * I print(“square of a current number is “, square)
  • 129. Pass statement for loop  The pass statement is null statement . nothing happens when the statements Is executed .it is used in empty functions or classes . when the interpreter finds a pass statements in the program it returns no operation. Syntax of pass statements: for elements in sequence: if condition: pass
  • 130. Pass statements for loop  Example of pass statements:- num=[1,4,5,3,7,8] for I in num: pass ------------------------------------------------------------------------------------------ ------------------------- months=[“January”,”june”,”march”,”april”] for mon in months: pass prints(months)
  • 131. Types of functions  Types of functions:- 1. Built in function 2. User-defined Function  Built in function:-The functions which are come along with python itself are called a built in function or predefined function.  Built in function are like:- range(), id() , type(), input() etc  Example:-python range function generates the immutable sequence of numbers starting from the given start integer to the stop integer.
  • 132. Types of functions  User-defined function:-  Functions which are created by programmer according to the requirement are called a user defined function.  Example of simple create function:- def sample(): x=10 print(x) sample()
  • 134. functions  Function definition  Every function start with a “def” keyword.  Every function should have a unique name.  Every function name are not a same any keyword.  User decide the parameters are given or not .  User decide the arguments are given or not but parameters and arguments are optional .  But the parameters and arguments are given the user so user given the parameters and arguments in parenthesis.  Every function name with out arguments should end with a (:).  Every function have return any value and return empty value.  Multi value return can be done in (Tuple)
  • 135. Functions calling  Function calling:-  So function calling is a simple process.  So call the function as a function name so user create a function add and user call the function is abc.  Other wise interpreter show the error .  So user call the function as a same name not use different name.  User given the arguments name and end the program user call the different arguments so this situation interpreter given the error.  End of the part user define the function and call the function are same name arguments and parameters include in the function are call the same name.
  • 136. functions  Simple example of call function :- def add(a,b): # define function and add parameters sum=a+b #third variable add the value return sum #use return statements a=int(input(“enter 1st value:-”) #user input values b=int(input(“enter 2nd value:-”) # user input values c=add(a,b) #call function Print(“the result is :-”,c) # print value
  • 137. functions  Simple example of calling function :- def add(): #function define a=10 #arguments and parameters b=20 #arguments and parameters c= a+b #use third variable and operation perform print(c) # print the value add() # function calling
  • 138. Return statement  The return statement is used to exit a function and go back to the place from where it was called.  It is called return statement.  Syntax of return statement:- return [expression_list]  This statement can contain an expression that gets evaluated and the values is returned .if there is no expression in the in the statement or the return statement itself is not present inside a function then the function will return the none object
  • 139. Return statement  Example of return statement in function:- def sample(num): if num>=0: return num else: return –num print((sample value(2)) print(sample value(-4))
  • 141. Types of arguments in functions Arguments of functions 1. Default arguments 2. Keyword arguments 3. Positional arguments 4. Arbitrary positional arguments 5. Arbitrary keyword arguments
  • 143. Default arguments  Default arguments are values that are provided while defining function.  The assignment operator = is used to assign a default value to the arguments  Default arguments become optional during the functional call  If we provide a value to the default arguments during function call it overrides the default value  The function can have any number of default arguments  Default arguments should follow non default arguments
  • 144. Default arguments  Example of default arguments:- def sample(name,age=23): print(“My name is:-”,name,”and age is :-,age) sample(name=“sourav”) _____________________________________________________________________ def hallo(name=“sourav”): print(“hyy”, sourav) hallo(“sunny”) Message()
  • 145. Default arguments  Example of default argument:- def sample(name,msg=“Good Morning”): print(“hello”,name +’,’+msg) sample(“sourav”) sample(“sunny”,What are you doing”)
  • 146. Keyword argument  Functions can also be called using keyword arguments of the form kwarg=value.  During a function call value passed through arguments need not be in the order of parameters in the function definition.  The keyword arguments should match the parameters in the function definition.  A keyword argument is an argument value passed to function preceded by the variable name and as equal sign.
  • 147. Keyword argument  Example of keyword arguments:- def abc(name,surname): print(“Hyy”,name,surname) abc(name=“sourav”,surname=“Arora”) abc=(surname=“kumar”,name=“sunny”)
  • 148. Keyword arguments  Example, of keyword arrguments:- def food(**Kwargs): print(Kwargs) food(a=“Apple”) food(fruits=“Mango”,vegitables=“Carrot”)
  • 149. Scope of variable  The scope of the variable depend upon the location where the variable is being declared.the variable declared in open part of the program may not be accessible to the other parts.  In pyton the variable are defined with the two types of scope:- 1. Global variable 2. Local variable  The variable defined outside any function is known to have a global scope whereas the variable defined inside a function is known to have a local scope.
  • 150. Local variable .Example of local variable in function:- def abc(): abc1=“hello I am going to delhi” print(abc1) abc() print(abc1)
  • 151. Global variable  Example of global variable:- def calculate(*args): sum=0 for arg in args: sum=sum+arg print(“the sum is:-”,sum) sum-=0 Calculate(10,20,30) Print(“value of sum outside the function:-”,sum)
  • 152. Positional arguments  During a function call values passed through arguments should be in the order af parameters in the function definition  This is called positional arguments  During a function call values passed through arguments should be in the order of parameters in the function definition  This is called positional arguments.
  • 153. Positional arguments  Example of positional arguments :- def add(a,b,c): return (a+b+c) print(add(10,20,30)) print(add(10,c=30,b=20)
  • 154. Required arguments  Required arguments are the arguments passed to a function in correct positional order.  The number of arguments in the function call should match exactly with the function definition  To call the function printme(),you definititely need to pass one arguments  The arguments is not provided in the function call or the position of the arguments is changed the python interpreter will show the error
  • 155. Required arguments  Example of required arguments:- def abc(name): message=“Hi”+name return message name=input(“Enter the name:-”) print(abc(name))
  • 156. Required arguments  Example of required arguments:- def sample(p,t,r): return(p*t*r)/100 P=float(input(“Enter the principle amount:-”)) r=float(input(“Enter the rate of interest:-”)) t=float(input(“Enter the time in years:-”)) print(“simple interest:-”,sample(p,r,t))
  • 157. Arbitrary positional arguments  Arbitrary positional arguments:- For arbitrary positional arguments an asterisk(*) is placed before a parameter in function definition which can hold non keyword variable length arguments These arguments will be wrapped up in a tuple . Before the variable number of arguments zero or more normal arguments may occur.
  • 158. Arbitrary positional arguments  Example of arbitrary positional arguments:- def add(*b): result=0 for I in b: result=result+I return result Print(add(10,20))
  • 159. Arbitrary keyword arguments  For arbitrary positional arguments a double asterisk(**) is placed before a parameter in a function in a function which can hold keyword variable length arguments.  Example of arbitrary keyword arguments:- def abc(**a): for I in a.items(): print(i) abc(number=5,colors=‘red’,fruits=“apple”)
  • 160. recursion  Python also accepts function recursion , which means a defined function can call itself.  Recursion is a common mathematical and programming concept.it means that a function calls.  The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates or one that uses excess amounts of memory or processor power.  In python we know that a function can call other functions it is even possible for the function to call itself.  These types of construct are termed as recursion functions.  The following image shows the working of a recursion function
  • 161. recursion  Syntax of recursion :- def func(): | | (recursive call) | func() ------
  • 162. recursion  Example of recursion of function:- def factorial(x): if x==1: return 1 else: return(x * factorial(x-1)) Num-3 Print(“the factorial of “,num, ‘is”,factorial(num))
  • 163. Lambda function  We use lambda functions when we require a nameless function for a short period of time  In python we generally use it as an arguments to a higher order function a function that takes in other functions as arguments  Lambda function as the anonymous function that is defined without a name.  Python allows us to not declare function in the standard manner by using the def keyword.  The anonymous function are declared by using thr lambda keyword  Lambda functions are used along with built in function like filter() map()
  • 164. Lambda function  Syntax of lambda function:-  Lambda arguments: expression  Example of lambda function;- X-lambda a:a+10 Print(x) Print(“sum=“,x(20))
  • 165. Lambda function  Example of lambda function:- def table(n): return lambda a:a*n n= int(input(“enter the number:-”)) b=table(n) for I in range(1,11) prnt(b(i)
  • 166. Filter function  The filter () function in python takes in a function and a list as a arguments.  The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to true.  Example of filter () function,, List=[1,5,4,6,8,11,3,12] List1=newlit(filter(lambda x: (x%2 ==0),list) Print(list1)
  • 167. Map function  The map() function in python takes in a function and a list  The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item  Python accepts a function and a list it gives a new list which contains all modified items returned by the function for each item
  • 168. Map function  Example of map function:- List=(10,20,30,40,50,60) new_list=list(map(lambda x:x**2,list) Print(new_list) ------------------------------------------------------
  • 169. Exception handling  Python has many built in exceptions that are raised when your program eccounters an error .  An exception is an event that occurs during the execution of programs that disrupt the normal flow of execution.  An exception is an event that occurs during the execution of programs that disrupt the normal flow of execution.  When a key is not found in a dictionary  An exception is a python object that represents an error  In python an exception is an object derives from the BaseExecption class that contains information about an error event that occurred withon a method .Exception Object Contains.
  • 170. Exception handling  Error type (Exception Name)  The state of the program when the error occurred  An error message describes the error event  For example let us consider a program where we have a function A that calls function B which in turn calls function C. if an exception occurs in function C but is not handled in C the exception passes to B and then to A  If never an error message is displayed and our program comes to a sudden unexpected halt.
  • 171. Exception handling  Examples are the few standard exceptions:- 1. FileNotFoundExceptions 2. ImportError 3. RuntimeError 4. NameError 5. NameError 6. TypeError
  • 172. Exception handling  Why Use Exception:-  Standardized error handling:-using built in exceptions or creating a custom exceptions with a more precise name and description you can adequately define the error event which helps you debug the error event.  Cleaner code:- Exceptions separate the error-Handling code from regular code which helps us to maintain large code easily.  Robust Application:-with the help of exceptions we can develop a solid application which can handle error event efficiently.  Exceptions Propagation:-the exception propagates the call stack if you don’t catch it.
  • 173. Exception handling  Example of Exception Handling:-
  • 175. Exception handling  The try and except Block to Handling Exceptions:-  When an exceptions occurs python stops the program execution and generates ab exception like error in the program like show error message in python console.  The doubtful code that may raise an exception an exception is called risky code.  Handle exceptions we need to use try and except block . risky code that can raise an exception inside the try block and corresponding handling code inside the except block.
  • 176. Exception handling  Syntax of exception handling:- try: statements in try block except: executed when exception occured in try block
  • 178. Exception handling  Example of try and except block:- try: a = 10 b = 0 c = a/b print("The answer of a divide by b:", c) except: print("Can't divide with zero. Provide different number")
  • 179. Exception handling  Example of exception handling;- try: a = int(input("Enter value of a:")) b = int(input("Enter value of b:")) c = a/b print("The answer of a divide by b:", c) except ValueError: print("Entered value is wrong") except ZeroDivisionError: print("Can't divide by zero")
  • 180. Exception handling  Multiple Exceptions with a single except clause:-  We can also handle multiple exceptions with a single except clause.  For that we can use an tuple of values to specify exceptions in an except clause.
  • 181. Exception handling  Example of multiple exceptions with a single except:- try: a =int(input(“Enter value of a:-”)) b =int(input(“Enter value of b:-”)) c=a/b print(‘the answer of a divide by b:”,c) except(ValueError, ZeroDivisionError): print(“Enter valid value”)
  • 182. Exception handling  Using Try with Finally:- 1. Python provides the finally block which is used with the try block statement. 2. The finally block is used to write a block of code that must execute 3. The try block raise an error or not. 4. Mainly finally block is used to release the external resource 5. The finally block provides a guarantee of execution.
  • 183. Oops object oriented programming  Python is a multi-paradigm programming language .it supports different programming approaches.  One of the popular approaches to solve a programming problem is by crating object  This is known as object –oriented programming (oops)  An object has two characterstics:  Attributes  Behaviour  Like parrot is a object as it has some properties:  Nme,age,color areattributes  Singing ,dancing as behaviour  The concept of oop in python focuses on crating reusable code.this concept is also known as DRY(Don’t Try Yourself)
  • 184. oops  Major principles of object oriented programming :- 1. Class 2. Object 3. Method 4. Inheritance 5. Polymorphism 6. Data abstraction 7. encapsulation
  • 185. oops  Class:- the class is a blueprint of objects . The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods For example if you have an employee class then it should contain an attributes and methods like an email id , name , age , salary , etc And class is a sketch of a program They use the class keyword to declare any class
  • 186. oops  Syntax of class:- class ClassName: statements | | | statements-N
  • 187. oops
  • 188. oops  Example of class :- class employee(): def __init__(self,name,age,id,slary): self.name=name Self.age=age self.id=id self.salary=salary emp1=employee(“sourav”,24,101,23900) Print(emp1.__dict__)
  • 189. oops  Class and object example of oops:- Class person: def __init__(self,name,gender,profession): self.name=name self.gender=gender self.profession=profession def show(self): print(“Name:-”,self,name,Gender:-”,self.gender,”,”Profession:-”,self.profession) def work(self): print(self.name,”working as a”, self.profession) Obj=person(“Sourav”,”Male”,”Python Developer”) Obj.show() Obj.work()
  • 190. oops  Object:-  A class is a collection of a object and it is a blueprint of program  Objects are an instance of a class it is an entity that has state and behaviour  An object is essential to work with the class attributes. The object is created using the class name.  When we create an object of the class .the object is also called the instance of a class  A constructor is a special methods used to create and initialize an object of a class
  • 191. oops  Example of object in class :- Class person: def __init__(salf,name,gender,profession): self.name=name self.gender=gender self.profession=profession def show(self): print(“Name:-”,self,name,Gender:-”,self.gender,”,”Profession:-”,self.profession) def work(self): print(self.name,”working as a”, self.profession) Obj=person(“Sourav”,”Male”,”Python Developer”) Obj.show() Obj.work()
  • 192. oops  Inheritance:-  Types of inheritance:- 1. Single inheritance 2. Multiple inheritance 3. Multilevel inheritance 4. Hierarchical inheritance 5. Hybrid inheritance
  • 193. oops  Single inheritance:-  In single inheritance a child class inherits from a single parent class . Here is a one child lass and one parent class. Create one parent class called class One and child class called class Two .
  • 194. oops  Example of single inheritance: Class vehicle: def vehicle_info(self): print(“inside vehicle class”) Class car(vehicle): def car_info(self): print(“inside car class): Car=car() Car.vehicle_info() Car.car_info()
  • 195. oops  Multiple inheritance:- In multiple inheritance one child class can inherit from multiple parent classes so here is one child and multiple parent classes. parent class parent class child class
  • 196. oops  Example of multiple inheritance:- Class person: def person_info(self,name,age): print(“name:”,name,”age:”,age) Class company: def company_info(self,company_name,location): print('Name:', company_name, 'location:', location) Class employee(person,company): def employee_info(self,salary,skil): print('Salary:', salary, 'Skill:', skill) Emp=employee() Emp.person_info(“sourav”,24) Emp.company_info(“Ex-Tech”,”Mohali”) Emp.employee_info(23900,”Python Developer)
  • 197. oops  Multiple inheritance:-  In multiple inheritance a class inherits from a child class or derived class.  Suppose three classes A,B,C,A is the superclass B is the child class of A , C is the child class of B in other words we can say a chain of classes is classes is called ,multiple inheritance parent class child class 1 child class 2
  • 198. oops  Example of multilevel inheritance:- Class vehicle: def vehicle_info(self): print(“inside vehicle class”) Class car(vehicle): def car_info(self): print(“inside car class): Class sportscar(car): def sports_car_info(self): print(“inside sportscar class”) Obj.car=suportscar() Obj.car.car_info() Obj.car.sports_car_info()
  • 199. oops  Hierarchical inheritance:- In hierarchical inheritance more than one child class is derived from a single parent class. In other words we can say one parent class and multiple child classes. parent class Child class 1 child class 2 child class 3
  • 200. oops  Example of hierarchical inheritance:- Class vehicle: def info(self): print(“this is vehicle”) Class car(vehicle): def car_info(self,na,e): print(“car name is:”,name) Class truck(vehicle): def truck_info(self,name): print(“truck name is:-”,name) Obj1=car() Obj1.info() Obj.car_info(“BMW”) Obj2=truck() Obj2.info() Obj.truck_info(“ford)
  • 201. oops  Hybrid inheritance: When inheritance is consists of multiple types or a combination of different inheritance is called hybrid inheritance. parent class child class1 child class2 child class3
  • 202. oops  Example of hybrid inheritance:- Class vehicle: def vehicle_info(self): print(“inside vehicle class”) Class car(vehicle): def car_info(self): print(“inside car class): Class truck(vehicle): def truck_info(self): print(“inside truck class”) Class sportcar(acr,vehicle): def sport_car_info(self): print(“inside sportcar class”) Obj=sportcar() Obj.vehicle_info() Obj.car_info() Obj.sport_car_info()
  • 203. oops  Polymorphism in python is the ability of an object to take many forms.  In simple words polymorphism allows us to perform the same action in many different ways.  For example jessa acts as an employee when she is at the office. However when she is at home she acts like a wife also she represents herself differently in different places.  Therefor the same person takes different forms as per the situation
  • 204. oops
  • 205. oops  Polymorphism in built in function len()  The built in function len() calculate the length of an object depending upon its type if an object is a string it returns the count of characters and if an objects is a list it returns the count of items in a llist.  The len () method treats on objects as per its class type  Example of len () function students=[“harry”,”garry”,”sharry”] School “abc school” Print(len(studnets)) Print(len(school))Śś
  • 206. oops
  • 207. Polymorphism with inheritance  Polymorphism is mainly used with inheritance .  In inheritance child class inherits the attributes and methods of a parent class  The existing class is called a base class or parent class and the new class is called a subclass or child class or derived class  Using method overloading polymorphism allows us to define methods in the child class that have the same name as the methods in the parent class the process of re-implementing the inherited method in the child class is known as method overloading.
  • 208. Method overloading  We have a vehicle class as a parent and a car and truck as its sub class  But each vehicle can have a different seating capacity speed etc  So we can have the same instance method name in each class but with a different implementation  This code can be extended and easily maintained over time
  • 210. Method overloading  Example of method overloading:- Class vehicle: def __init__(self,name,color,price): self.name=name self.color=color self.price=price def sjow(self): print(“details;-”,self.name,self.color,self.price) def max_speed(self): print(“vehicle max speed is 150”) def change_gear(self): print(“vehicle change 6 gear”) Class car(vehicle): def max_speed(self): print(“car max speed is 300”) deef change_gear(self): print(“carchange & gear”) car=car(“car x1”,”red”,305000) Car.show() Car.max_speed() Car.change_gear() Vvehicle=vehicle(truck x1”, “white”, 758000) Vehicle.show() Vehicle.max_speed() Vehicle.change_gear()