PYTHON NOTES
PYTHON NOTES
Eg:1print("hello world")
Eg:2
print(2+2)
Eg:3
print("2+3="+str(2+3))
print("2+3=",2+3)
print("2+3=",(2+3))
Eg:4
print(1+2+3)
print('1+2+3')
print('1'+'2'+'3')
print("1+2+3")
print("1"+"2"+"3")
Eg:5
print(2*5)
print(2**5) #2 to the power of 5
print(9**(1/2)) #squareroot of 9
Eg:6
print(1,2,3) # by default: print(1,2,3,sep=' ',end='\n')
print(1,2,3,sep='#')
print(1,2,3,sep='#',end='$')
print('2+5')
print()
print(eval('2+5'))
VARIABLE:
a variable allows you to store a value by assigning it to a name
which can be used to refer the value later in the program
a=5 eno=101 sname="siva" mark=45.67
rules for variable name:
o starts with alphabet or _
o can't contain special characters(#,@,...) except _ (underscore)
o number must be in middle or last
Static Typing:
variable belongs to specific datatype throughout the life time
variable must be decleared before use ,with specific datatype
Eg: In C lang:
int a;
- a is integer type .
- can have numbers only and we cant store either
decimal, character or string
Dynamic Typing:
variable didn't belongs to specific datatype throughout the life time
no need to specify datatype
Eg:In Python lang:
a=5
now a is integer
a=4.5
here a is float
a="hello"
then here a is string
DATA TYPES:
int
float
long
complex(complex number)
boolean(True/False)
Eg:1
a='hai'
print(a)
a="hai"
print(a)
note:
cant overlap ' and "
a=' "hai' "
a=" 'hai" '
these two statements produce error: "EOL while scaning string literel"
Eg:2
a='\'hai\''
print(a)
a="\"hai\""
print(a)
Eg:3(doc string)
a="""hai
hello"""
print(a)
Eg:4
a='hai \n hello \t bye '
print(a)
Eg:5
print('print("print")')
print("print('print')")
Eg:6
a=1+2+\
3+4+5
print(a)
a=1+2\
+3+4+5
print(a)
print("abcdefgh\
ijklmnopqrstuvwxyz")
Eg:7
a=1
b=2
c=3
print(a+b+c)
a=1;b=2;c=3
print(a+b+c)
a,b,c=1,2,3
print('output is', a+b+c)
a=b=c=4
print(a+b+c)
Eg:8
A=5
a=6
print(A)
print(a)
Eg:9
a=5
a=a+5
print(a)
a="7"
a=a+"0"
print(a)
Eg:10
z=10
print(z)
z=25
print(z)
del z
print(z)
Eg:11
z=10
print(z)
del z
#print(z)
z=88
print(z)
PREDEFINED FUNCTION
1.type conversion
int(), float(),str() are the functions used to convert respective types
Eg:1
a='2'
b='3'
c=a+b
print(c)
print(int(a)+int(b))
a='2.25'
b='3.23'
print(float(a)+float(b))
a=2
b=3
print(str(a)+str(b))
2.input function:
to get values (input) from users
all inputs are in string format
Eg:2
input
a=input("enter a number: ")
b=input("enter a number: ")
c=int(a)+int(b) process
print(c) output
Note:
print(int(input("enter a number: ")) + int(input("enter a number: ")))
Eg:3
z="*"*20
print(z)
z="12"*2
print(z)
Eg:4
z="PYTHON"*int(input("enter a number"))
print(z)
z=float("12"*int(input("enter a number")))
print(z)
Note:
z=float("A"*int(input("enter a number")))
print(z)
3.Isinstance function:
sy: isinstance(variable_name,datatype)
to check whether the given variable belongs to given datatype , if yes
return "True" else "False"
Eg:5
c=5+3j
print(isinstance(c,complex))
a=34
print(isinstance(a,int))
z=34.5
print(isinstance(z,complex))
4.type function:
sy: type(variable_name or value)
to return datatype of the variable or value
Eg:6
z=12
print(type(z))
z=1.2
print(type(z))
z="12"
print(type(z))
z="Hello"
print(type(z))
print(type("33"))
print(type(33))
Number System:
Decimal Numbers: 0,1,2,3,4,5,6,7,8,9 (deci – 10)
Binary Numbers: 0,1(bi -2)
Octal Numbers: 0,1,2,3,4,5,6,7(octa- 8)
HexaDecimal Numbers: 0,1,2,3,4,5,6,7,8,9,A(10),B(11),C(12),D(13),E(14),F(15)
(hexa- 6, deci-10)
Eg:1
print(0b1101011) #107
print(0xFB + 0b10) #251+2 =253
print(0o15) #13
Eg:2
x='3+5j'
y=complex(x)
print(y)
Note : if given value is not complex format then the following error raised
ValueError: complex() arg is a malformed string
Eg:
'3+5j' -> 3+5j
'3+j' -> 3+1j
'3' -> 3+0j
'3+' or '3+ku' or "3 5j"-> malformed string
Operators
Unary Operators – 1 operand (not available in python)
Binary Operators- 2 operand
o arithmetic operator
o assignment operator
o equality operator
o conditional operator
o logical operator
o in-place operator
arithmetic operator :
+ - * / // %
Eg:1
a=5
a=a+5
print(a)
a=a-5
print(a)
a=a*5
print(a)
a=a/5 #float division
print(a)
a=a//5 #integr division(quotient value)
print(a)
a=a%5 #remainder
print(a)
assignment operator(=)
evaluate right side and store into left side
equality operator(==)
check whether both sides values are equal
Eg:2
a=2
print(a)
print(2==3)
print('2'=='3')
conditaniol operator
> < >= <= !=
Eg:3
print(7>=7)
print(7<7.0)
print(7<=7.0)
print(7>=7.0)
print(7!=7.0)
Eg:4
print((2<5) and (2<7)) # True if both conditions are true
print((7<5) or (2<7)) #True if any one condition is true
print(not(2<5)) # True if codition if false , False if condition is true
Eg:5
x=3
x+=8 #x=x+8
print(x)
x-=8 #x=x-8
print(x)
x*=8 #x=x*8
print(x)
x/=8 #x=x/8
print(x)
Conditional statements
if statement(simple if)
if..else statement
elif statement
nested if
Note:
switch case is not available in Python
if statement
to run code if a certain condition holds(true) otherwise not
syntax:
if expression:
statements
Eg: 1
a=13
if a>3:
print(a , "is greater than 3")
print("end")
Eg:2
a=31
if a>5:
print(a,end=" ")
print("is greater than 5")
if-else statement
sy:
if condition:
statements
else:
statements
Eg:3 to find a given number is greater than 5 or not
a=int(input("enter a number"))
if a>5:
print(str(a) + "is greater than 5")
else:
print(str(a) + "is smaller than 5")
elif statement
sy:
if condition:
statements
elif condition:
statements
elif condition:
statements
:
:
else:
statements
Note: else part is optional
Eg:8
a=int(input("enter a number"))
if a==5:
print(str(a) + "is equal to 5")
elif a<5:
print(str(a) + "is smaller than 5")
else:
print(str(a) + "is greater than 5")
print(“Done”)
Eg:12
a=input("Color:")
if a=='r':
print("primary color")
elif a=="g":
print("primary color")
elif a=="b":
print("primary color")
else:
print("not primary color")
print("end")
Assignments:
Get student name and 5 subjects mark . print grade
If average mark >=80 A
60-79 B
40-59 C
<40 D
Nested if
sy:
if(condition):
st
if(condition)
st
Eg:13 nested if
a=int(input("enter a number"))
b=int(input("enter a number"))
c=int(input("enter a number"))
if(a>b):
if(a>c):
print(a)
else:
print(c)
else:
if(b>c):
print(b)
else:
print(c)
More Examples
Eg:14 BMI Calculation
a=str(input("What is your NAME??? "))
b=float(input("What is your Weight in kg? "))
c=float(input("What is your Height in metre? "))
bmi=round(b/(c**2),2)
if(bmi<25):
print("bmi: "+str(bmi))
print(str(a)+" is not overweight")
else:
print("bmi: "+str(bmi))
print(str(a)+" is overweight")
print("THANK YOU")
Looping statements
to execute statements repeatedly while conditions holds
for, while
while loop:
Syntax:
while condition:
statements
else:
statement
Note: else is optional. else executed when condition false
Eg:1 to print 1- 10
1 INITIAL VALUE
2
3
4
5
6 6-5 1 INCREMENT VALUE
7
8
9
10 FINAL VALUE
a=1
while a<=10:
print(a)
a=a+1
Eg:2 to print 10 to 1
a=10
while a>=1:
print(a)
a=a-1
Eg:8
a=int(input("enter initial number"))
b=int(input("enter final number"))
c=int(input("enter divider"))
while a<=b:
if((a%c)==0):
print(a)
a=a+1
break:
to terminate loop execution
Eg:9
a=1
while a<=10:
if(a==5):
break
print(a)
a=a+1
print("End")
continue:
to skip loop remaining lines and goto loop start
Eg:10
a=0
while a<=10:
a=a+1
if(a==5):
continue
print(a)
print("End")
print("End")
for loop:
range function:
range(initial_value,final_vlaue,increment_value)
range(initial_value,final_vlaue)
range(final_vlaue):
eg:
range(1,5,1) -> 1,2,3,4
range(5,1,-1) -> 5,4,3,2
range(2,11,2) -> 2,4,6,8,10
range(1,5) ->1,2,3,4
range(5) -> 0,1,2,3,4
Note: initial_value,increment_value are optional
default values
initial_value ==> 0
increment_value==>1
Eg:11
for i in range(1,10,1):
print(i)
for i in range(1,10):
print(i)
for i in range(10):
print(i)
for i in range(10,1,-1):
print(i)
Eg:12
a="csc"
for i in a:
print(i)
Assignment:
convert all while program(what we seen) into for
product of n numbers
find sum of odd numbers and even numbers upto a given number
Eg:60_1
for i in range(5,0,-1):
for j in range(1,i+1):
print(i,end=" ")
print("\n")
Eg:61_1
for i in range(5,0,-1):
for j in range(1,i+1):
print(j,end=" ")
print("\n")
Eg:15
for i in range(1,6):
for j in range(1,i+1):
print(j,end=" ")
print("\n")
Eg:62_1
for i in range(5,0,-1):
for j in range(1,i+1):
print(“*”,end=" ")
print("\n")
Eg:16
for i in range(1,6):
for j in range(1,i+1):
print("*",end=" ")
print("\n")
Eg:17
for i in range(1,6,):
for j in range(1,i+1):
print(j,end=" ") print(i,end="
") print(“*”,end=" ")
print()
for i in range(4,0,-1):
for j in range(1,i+1):
print(j,end=" ") print(i,end="
") print(“*”,end=" ")
print()
Eg:18
K=1
for i in range(1,5):
for j in range(1,i+1):
print(K,end="")
K=K+1
print()
K=65
for i in range(1,5):
for j in range(1,i+1):
print(chr(K),end="")
K=K+1
print()
functions
group of st. that perform specific task
function Definition:
def fun_name(params):
""" doc_string"""
statements
Note: doc string is optional
function call:
fun_name(values)
to get doc_string:
print(fun_name.__doc__)
Eg:1
def display():
"""this is sample function
named display"""
print("Display Function")
Eg:2
def addition():
a=int(input("No1:"))
b=int(input("No2:"))
c=a+b
print("Addition: " ,c)
addition()
Eg:3
def addition(x):
for i in range(1,x+1):
a=int(input("No1:"))
b=int(input("No2:"))
c=a+b
print("Addition: " ,c)
z=int(input("Count:"))
addition(z)
Eg:4
def add(a,b):
c=a+b
return c
z=add(22,33)
print("Add:" + z)
print("Add:" + add(33,44))
a=int(input("enter a number"))
b=int(input("enter a number"))
print(add(a,b))
Default arguments:
to provide default value to the argument in fun.def
in function call , the values are present for default parames than its
assigned to default parameters else default values are stored
Eg:5
def add(a=10,b=20,c=30):
return a+b+c
print(add(1,2,3))
print(add(1,2))
print(add(1))
print(add())
Eg: 6
def add(*a):
s=0
for x in a:
s=s+x
print(add(1,2,3,4,5,6))
print(add(1,2,3,4,5))
print(add(1,2,3,4))
print(add(1,2,3))
print(add(1,2))
print(add(1)
Eg:8
def add(x,y,*a):
print("formal param x:" + str(x))
print("formal param y:" + str(y))
print("arbitary argument a values :")
for z in a:
print(z)
add(1,2,3,4,5,6)
add(1,2,3,4,5)
add(1,2,3,4)
Eg:9
def addfun(x,*y):
s=0
for i in y:
s=s+i
print(x,s)
keyword argument(**kwargs)
Eg:10
def add(**a):
for y in a:
print(str(y) + " = " +a[y] )
add(Tamil1="200", English="300",Maths="400")
Recursive Function:
function calls itself
Note:
def show1():
print("Show1")
def show2():
print("Show2")
show1()
show2()
#------------------------------------
def show1():
print("Show1")
show2()
def show2():
print("Show2")
show1()
#-----------------------------------
#calling function from its own
#unlimited calling
def show1():
print("Show1")
show1()
show1()
#------------------------------------
Eg: 11 to find factorial without recursive function:
def fact(x):
p=1
for y in range(1,x+1):
p=p*y
return p
print(fact(5))
Eg:15
dis=lambda a,b,c: a*b*c
z=dis(1,2,3)
print(z)
Eg:16
deepika =lambda a,x: a%x
print(deepika(12,5))