Master in Python
Master in Python
PYTHON PROGRAMMING
• Introducing Python-
print("Hello")
➢ Multiparadigm Support
➢ Dynamically Typed
x = 10
y = "geeks"
x = "python"
➢ print () in Python –
A some function is a set of instructions that take
some input from us. do some work on those
Parament and product some output .
. Example -
print ("Hello")
print ("Welcome", "to", "GfG")
print()
print("Hope you are enjoying Python")
.Output- Hello
Welcome GFG
Hope you are enjoying Python
Output- 10-04-2024
➢ Variables in Python -
Variable is a name location. Python variable is
also known as an identifie and used to hold valu.
In python we don’t need to specify the type of
variable because python is a infer language and
smart enough to get variable type .
tax = 18
total-price price + tax
print (total-price)
Output - 118
x = 10 10 y
y = "geeks" geek z
z= 20 20
z
if we say, w = z
then 20 wx
but if , w= 30 30 w
Eg – print (x)
o/p- name error : name is not assigned
➢ Input () in python –
This function is used to take input from the user
. Example – name = input (“ Enter the name =”)
print (“ welcome” + name )
O/p - enter the name = WEST BENGAL
Welcome WEST BENGAL
J=[10,20,30]
( array and dynamically
print(type (j)) add remove items. Items
are stored in continuous
location. )
T = ( 10, 20, 30) (11 is also like a list, the
Print (type (t)) difference is your can’t
Modify once you created
A tuple. These are immutable)
Implicit Explicit
Eg- a=10 Eg- s =”135”
B= 1.5 J=1+int(s)
c=a+b F=float(s)
print(s) Print(i)
d=true Print(f)
e= a+b
print(e)
Text false
Expression
True .
Body Of If
Example – if 10>5:
Print (“10 is greater then 5”)
Print (“program ended”)
o/p - 10 is greater then 5
program ended.
➢ If else statement - in condition if statement the
additional block of code is merged as else
statement which is perform when if condition is
false .
Syntex – if (condition)
# executes this block if
# condition is true
else:
# Executes this block if
# condition is false
. Flowchart -
Text false
Expression
True .
Body Of else
Body Of If
Example – x=3
If x==4: Statement just below if
Print(“yes”)
Else:
Print(“no”)
Example – you can also chain if else statement with more
than one condition .
Latter = “a”
If later == “B”:
Else:
If later == “c”
print ( “ latter is c”)
else :
If latter == “A”:
print (“ latter is A “ )
Else
print (“latter is “t A, B and C” )
o/p – latter I A
Example – num = 10
If num >5:
print (“ bigger then 5”)
If num <=15:
print (“between 5 and 15” )
o/p - bigger then 5
between 5 and 15
➢ if – elif statement - shortcut of if -else chain ,
while using if- else statement at the end else
block is added which is performed if none of the
above if -else statement is true.
syntax - if ( condition ):
statement
elif( condition):
statement
.
else :
statement
Example – latter == “A”
If latter == “b”
Print (“latter is b” )
Elif latter==”c”
Print(“latter is c” )
Elife latter == “A”
else :
print(“latter isn’t A,B or C”)
o/p- latter is A
➢ Arithmetic operators – Thay are used to perform
mathematical operations like additional, subtraction,
multiplication , division.
X and y
false true
X = true
False output
fals true
X = true
true False
X = true
true output
Example- false true
a=10 X = true
b= -10
c= 0 False output True output
if a>0 or b>o:
print ("Either of the number is greater Ihan 0")
else:
print ("No number is greater than o")
if b>o or c>0:
print ("Either of the number is greater than 0")
else:
print ("No number is greater than O")
Not X
True False
X= true
Example- x=5
If(type(x) is not int):
print (“true”)
else:
print(“false”)
#print true
X=5.6
If (type(x)is not int ):
Print(“true”)
else:
Print (“false”)
o/p- false
True
Example - a = 10
b=4
#Print bitwise AND operation
print ("a & be, a&6)
# Print bitwise OR operation
print ("a/b=", a/b)
#Print bitwise NOT operation
Print(“~a=”,~a”)
#Print bitwise XOR operation
print ("a^b =", a^b)
a) Bitwise Right Rep Shift (>>) - Shifts the bits of the no. to the
right and fills o on void left (fills I in the case of a negative
number ) as a result. Similar effect as of dividing the no. with
some power of two.
Example - a=10=0000 1010 (Binary)
a>>1=0000 0101 =5
Example – a=-10=1111 0110(Binary)
a>>1=1111 1011=-5
def-invert-(self):
print ("Invert operator overloaded")
returnˉ self. Value
# Driver's code
If-name == "_main_":
a = Geek (10)
b= Geek (12)
print (a & b)
print (a/b)
print (a ^ b)
print (a<<b)
print (a>>b)
print (~a)
* Loops in Python-
- While Loop - It is used to execute a block of statements
repeatedly until a given condition is satisfied. And when the
condition becomes false, the line immediately after the loop in the
program is executed.
Test
False
Expre ssion
True
Statements Exits while loopExpression
o/p- 4
3
2
1
In this , we have run a while loop over a list that will run
until there is an element present in the list,
Example-3 single statement while block
Just like if block , if block , if the while block consists of
single line . if there are multiple statement in the block
that make up the loop body , they can be separated by
semicolons (;) .
Count = 0
while (count<5): count + = 1; print (“Hello Geek”)
0 0 1 2 3 4 5 6
Output
start stop
Example - Demonstration of python range (start , stop )
# printing a natural
# number from 5 to 20
for I in rang (5, 20):
print(I , and = “”)
o/p- 5 6 78 9 10 11 12 13 14 15 16 17 18 19
c. range (start, stop, step)
when the user called range () with there aruments, the
user can choose not only where the series of number will
start and stop , but also how big the different will be
between the step , then range() will automatically behave
as if the step is l. in this example , we are printing even no
. between o and 10 so we choose out string point from 0
(start =0) and stop the serics al 10 (stop = 10 ). For printing
on even number the difference between one number and
the next number must be 2 (step =2) after providing a step
we get the following output (0, 2, 4, 6, 8)
star stop
Python range (0, 10, 2)
01 2 3 4 5 6 7 8 9 10
2 step
02468
O/P-
Example – Demonstration of python range ( start, stop ,step)
Note- in python , for loop only implement the collection – based iteration.
d= dict()
d['x y z'] = 123
d[a b c] = 345
for i in d:
print("%s %d" % (i, d(i))
True
Brack Yes
No
Loop test a
Expression
Condition to True
continue continue
next iteration
False
0/b - 1 2 3 4 5 7 8 9 10
Note - The Continue Statement Can Be Used With Any Other Loop Also Like "While Loop"
Similarly As It Is Used With 'For Loop" Above.
* Nested Loop - with for and while loops we can create nested
loop . nested loop means loops inside a loop. For example ,
while loop inside the for loop , for loop inside the loop , etc.
Syntax - Outer loop Expression :
Inner- loop Expression:
Statement inside outer loop
Example - x= [1,2]
Y = [4,5]
For I in x :
For j in y :
print (I , j )
o/p - 14
15
24
25
Example –
# Multiplication Table
# Running outer loop from 2 to 3
For I in rang (2,4):
# printing inside the outer loop
# running inner loop from 1 to 10
For j in range the inner loop
print ( I , “x”, j “=” , I * j )
# printing inside the other loop
print()
o/p - 2*1=2 ………………..2*10=20
3*1 =3……………….. 3*10= 30
Example - # Initialize list and list 2.
# with some strings
list1: ['lam', 'You are']
list 2: ['healthy', 'fine', 'geek']
# Store length of list 2 in list 2-size
list 2. size jen (list 2)
# Running outer for Joop to
# iterate through a list 1
for item in list 1:
# Printing outside inner loop
print("start outer for loop")
# initialize couter i with O 10
I =0
# Running inner while loop to
# iterate through a list 2
while (i< list 2 size):
# Printing inside inner loop
print (item, list 2[i])
# Incrementing the value of i
i=i+1
# printing outside inner loop
print ("end for loop")
O/p- start outer for loop
I am healthy
I am fine
1 am geek
end for loop
start outer for loop
You are healthy
You are fine
You are geek
End for loop
In this example , we are initializing two lists with some
string. Store the size of list 2 in list 2- size using len()
functing and using it in the while loop as a counter. After
that run on outer for loop to iterate over list 2 using list
indexing that we are printing each value of list 2 for every
value of list 1 .
• Function in python –
Python function is a block of statement that return
the specific task.
1-Types of Arguments-
Print (String1)
# Creating String with Triple
# Quotes Allows Multiple Lines
String1= “Geeks
For
Life”
Print (“In Creating A Multiline Sting:”)
print (strin1)
O/P - String with the use of single quotes:
Welcome to the geek world
String with the use of double quotes:
I’m a geek
String with the use of Triple quotes:
geeks
For
life
-Accessing character in python string-
In python, individual characters of a string can be
accessed by using the method of Indexing. Indexing allows
negative address references to access characters from the
back of the string, eg.1 refers to the last char, -2 refers to
the second last char and so on.
While accessing an index out of the range will cause an
Index Error. Only Integers are allowed to be passed as an
index. Float or other types that will cause a Type Error.
• List Introduction –
Python List Are Just Like Dynamically
Sized Arrays, Declared in Other Language (C ++, Java). In
A Simple Language, It Is Aa Collection of Things, Enclosed
With [] And Separated by Commas.
The List Is a Sequence Data Type Which Is
Used to Store the Collection of Data. Tuples And Strings
Are Other Types of Sequence Data Types.
- del keyword – del is a key word and remove (), pop () are in
built method.
- remove () method delete value or object from the list using
value.
- the del and pop () delete values or objects from list using and
objects.
- the del keyword deletes any variable, or list of value from a
list.
Syntax –
del list _ name[index] # to delete single value
del list _name # to delete whole list
-Nested Dictionary –
Dict = { 1: ‘Geeks’, 2: ‘For’, 3: {‘A’: ‘Welcome’,
‘B’: ‘To’, ‘C’: ‘Geeks’ {}
Print (Dict)
List = []
for character in ‘ Geeks 4 Geeks!’:
list. Append(character)
print (list)
O/P- [‘G’, ‘e’, ‘c’, ‘k’, ‘s’, ‘4’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘!’]
Obj = dog ( )
Before diving deep into object and classes let us understand some
basic keyword that will we used while working with objects and
classes.
not.
3. Setattr()- used to set an attribute.
4. Delatter()- used to delete an attribute.
➢ Class method vs static method-
Class method is a method that is bound to the class
and not the object of the class.
They have the access to the state of the class as it
tasks a class parameter that to the class and not the
object instance.
It can modify a class state that would apply across
variable that will be applicable to all the instances.
Static method dosen’t receive on implicit first
argument.
• Polymorphism –
It means having many forms. In programming
Polymorphism means the same function name (but
different signature) being used for different types.
Class bird :
Def intro (self):
print (“there are many types of birds”)
Def flight (self):
print (“most of the bird can fly but some
cannot”)
Class sparrow (bird):
Def flight (self):
print (“sparrows can fly”)
Class ostrich (bird):
Def flight (self):
print (“ostriches cannot fly”)
Obj_ bird = bird ( )
Obj_ spr = sparrow ( )
Obj_ ost = ostrich ( )
Obj_ bird = intro ( )
Obj_ bird = flight ( )
Obj_ spr. Intro ( )
Obj_ spr. Flight ( )
Obj_ ost. Intro ( )
Obj_ ost. Flight ( )
• Abstract class –
An abstract class can be considered as a blue
print for other classes. It allows you to created a set of
method that must be create with in any child classes built
from abstract class. A class which contain one or more
abstract method is a method that has a declaration but
does not have an implementation. While we are designing
large functional units we use an abstract class.
# Driver Code
R = Triangle ()
R. = Noof Sides ()
K = Quadrilateral ()
K. = Noof Sides ()
R = Pentagon ()
R = Noof Sides ()
K = Hexagon ()
K = Noof Sides ()