Program:
Note: Python have 33 reserved words which all in
lower case except 3(True, False and None)
import keyword
print([Link])
O/P =
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class'
, 'continue', 'def', 'del', 'elif', 'else', 'except', 'finall
y', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda'
, 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
Program:
a = 10;
b = 1.2;
l = [1,2,3];
t = (5,14,25);
i = 1+2j
fi = 1+2.2j
t = True; f = False;
Name = 'sachin'
Last_Name = "Gupta"
Combine = '''I am looking
you'''
print('1. ',type(a));
print('2. ',type(b));
print('3. ', type(l));
print('4. ',type(t));
print('5. ',type(i));
print('6. ',type(fi));
print('t=',type(t),'f=',type(f))
print('Name= ', Name,type(Name))
print('Last_Name = ',Last_Name ,type(Last_Name))
print('Combine',Combine,type(Combine))
O/P=
1. <class 'int'>
2. <class 'float'>
3. <class 'list'>
4. <class 'bool'>
5. <class 'complex'>
6. <class 'complex'>
t= <class 'bool'> f= <class 'bool'>
Name= sachin <class 'str'>
Last_Name = Gupta <class 'str'>
Combine I am looking
you <class 'str'>
Program:
Note: Python is a case sensitive language, A and a
both are different variable.
a =10;
A =20;
print(a,A)
O/p =410 20
Program:
Note: Python have many inbuilt function like
id(),type() and print() etc.
Id(): This is function is used to provide the address
of that variable.
a =10;
A =20;
print(type(a))
print(id(a))
print(id(A))
O/P =
<class 'int'>
10105376
10105696
Note: what is PVM?
Ans: It is nothing, it’s Python Virtual Machine
Program:
Note: We can use both E and e for exponential
The main advantage of exponential form is we can
represent big values in less memory.
a = 1e1;
print(a);
b = 1E2
print(b)
O/p
=10.0
100.0
***Note:
We can represent int values in decimal, binary,
octal and hexa decimal forms. But we can
represent float values only by using decimal form.
a = 0b.11;
print(a)
O/P= Trying to give decimal in binary, getting
error. So decimal can only use with float data type
otherwise will get error.
File "[Link]", line 1
a = 0b.11;
SyntaxError: invalid token
Program:
Note:
In the real part if we use int value then we can specify
that either by decimal,octal,binary
or hexa decimal form.
But imaginary part should be specified only by using
decimal form.
a = 0b11+5.4j
A = 0b11+5j
print(a)
print(A)
O/P =
(3+5.4j)
(3+5j)
Program:
ssssss
Note: Python have facilities to print separate real and
imaginary part.
a = 0b11+5.4j
print('Print will only int part',[Link]);
print('Print will on;y imaginary part',[Link])
O/P =
Print will only int part 3.0
Print will on;y imaginary part 5.4
Program:
a=10
b=20
a = a<b
print(a)
O/P =
True
Program:
Note: in-short True =1 and False = 0
print(True);
print(False);
print(True+False);
print(True-True);
print(False-True);
print(True+2);
O/P =
True
False
-1
Program:
print('name'*3)
O/p=
namenamename
Type
Casting
Program:
Note: Python have facilities to convert data type from
one to other
Functions:
1. int()
2. float()
3. complex()
4. bool()
5. str()
Note for int() function:
1. We can convert from any type to int except complex type.
2. If we want to convert str type to int type, compulsary str should contain only
integral
value and should be specified in base-10
Note for float() function:
1. We can convert any type value to float type except complex type.
2. Whenever we are trying to convert str type to float type compulsary str should
be
either integral or floating point literal and should be specified only in base-10.
s = 1;
print(str(s))
print(type(s))
# now it will convert into string formate
p=str(s)
print(type(p))
O/P =
1
<class 'int'>
<class 'str'>
Error:
Program:
Note: We can not convert complex number to int
b= 2+3j;
print(int(b));
O/P =
Traceback (most recent call last):
File "[Link]", line 2, in <module>
print(int(b));
TypeError: can't convert complex to int
Program:
Note: We can not also convert character(like
‘n’ ,’java’ etc) into Int.
c = 'ten';
print(int(c));
O/P =
Traceback (most recent call last):
File "[Link]", line 2, in <module>
print(int(c));
ValueError: invalid literal for int() with base 10: 'ten'
Program: Use of Complex() function
# first Form
c =10
print(complex(c));
# Second Form
print(complex(5,2));
# con't be convert
print(complex('ten'))
O?P =
(10+0j)
(5+2j)
Traceback (most recent call last):
File "[Link]", line 7, in <module>
print(complex('ten'))
ValueError: complex() arg is a malformed string
Program: Bool() function
print(bool(True));
print(bool(False));
print(bool(0))
print(bool(1))
print(bool(12))
print(bool(10+2j))
print(bool('True'))
print(bool("False"))
print(bool('fdf'))
O/P =
True
False
False
True
True
True
True
True
True
Note:
Python have multiple data types.
Python contains the following inbuilt data types
1. int
2. float
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Note:
[Link]()
to check the type of variable
2. id()
to get address of object
Program: bytes data type
Conclusion 1:
The only allowed values for byte data type are 0 to
256. By mistake if we are trying to
provide any other values then we will get value
error.
Conclusion 2:
Once we creates bytes data type value, we cannot
change its values,otherwise we will get
TypeError.
Conclusion 3:
In general we can use bytes and bytearray data
types to represent binary information
like images,video files etc
p = [10,25,16]
c = bytes(p)
print(type(c))
for i in c:
print(i)
O/P =
<class 'bytes'>
10
25
16
Program:
p = [10,25,300]
c = bytes(p)
for i in c:
print(i)
O/P =
Traceback (most recent call last):
File "[Link]", line 2, in <module>
c = bytes(p)
ValueError: bytes must be in range(0, 256)
Note:
bytearray Data type:
bytearray is exactly same as bytes data type
except that its elements can be modified.
list and tuple data type: check Durga notes,Page no 24.
Program: range data type
print(range(10))
c = range(3);
for i in c:
print(i)
O/P =
range(0, 10)
Program:
Note: range(a,b,c)
a = start value from a
b = end value at b
c = incremental value
c = range(1,11,2);
for i in c:
print(i)
O/P =
1
Program:
Note:
Range() function can be convert into list.
c = range(1,11,2);
l = list(c)
print(type(l))
print(l)
O/P =
<class 'list'>
[1, 3, 5, 7, 9]
Note:
We can access elements present in the range Data
Type by using index.
r=range(10,20)
r[0]==>10
r[15]==>IndexError: range object index out of
range
We cannot modify the values of range data type
Program: None data type
Note:
None means Nothing or No value associated.
If the value is not available,then to handle such
type of cases None introduced.
It is something like null value in Java.
def m1():
a=5;
print(m1())
O/P =
None
Operat
ors
Note:
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise oeprators
5. Assignment operators
6. Special operators
Program: Arithmetic operator
Note:
% ===>Modulo operator
// ==>Floor Division operator
** ==>Exponent operator or power operator
a =5
b=2
print(a+b);
print(a-b);
print(a/b);
print(a//b);
print(a*b)
print(a%b)
print('sqaure of a: ',a**b)
O/P =
7
2.5
10
sqaure of a: 25
Program:
Note:
We can use +,* operators for str type also.
If we want to use + operator for str type then
compulsory both arguments should be str
type only otherwise we will get error.
a ='name'
b = 'last_name'
print(a+' '+b)
print(a*10)
O/P =
name last_name
namenamenamenamenamenamenamenamenamename
Program:Relationship operator
a =100
b =20
print(a>b)
print(a>b is False)
O/p =
True
False
Eg:
1) print(True>True) False
2) print(True>=True) True
3) print(10 >True) True
4) print(False > True) False
5)
6) print(10>'durga')
7) TypeError: '>' not supported between instances
of 'int' and 'str'
Program: Logical Operators:
and, or ,not
True and False ==>False
True or False ===>True
not False ==>True
Program:
print(10 and 20 )
print(0 and 20);
print(10 or 20);
print(0 or 20);
print( not 10);
print(not 0);
O/P =
20
10
20
False
True
Program:
a = input('Enter first value');
b = input('Enter first value')
if(int(a)==10 and int(b) ==20):
print('hello')
O/P=
Enter first value10
Enter first value20
hello
Ternary Operator:
Syntax:
x = firstValue if condition else secondValue
a=10;
b =20;
min = a if a<b else b
print(min)
O/P =10
Program:
a=10;
b =20;
min = 30 if a<b else b
print(min)
O/P =30
Program: Max value print
a = int(input('Enter first value: '));
b = int(input('Enter sceond value: '));
c = int(input('Enter third value: '));
max = a if a>b and a>c else b if b>c else c
print(max)
O/P =
Enter first value: 2
Enter sceond value: 25
Enter third value: 3
25
Program:
Special operators:
Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
Program: Identity Operators
1. is
2. is not
a=10
b =10
c = 20
print(id(a));
print(id(b));
print(id(c));
print(a is b)
print( b is a)
print(b is c , a is c)
print(b is not c, a is not c)
O/P =
10105376
10105376
10105696
True
True
False False
True True
Program: diffrnce between is and == operator
Note:
List has same value but it will not allocated to
same address.
Note:
We can use is operator for address comparison
where as == operator for content
comparison.
a = 10
b = 10;
print(id(a),id(b))
print(a==b, a is b)
a = 'name';
b = 'name';
print(id(a), id(b))
print(a==b, a is b)
l = []
l2 = []
print(id(l),id(l2))
print(l==l2, l is l2)
t = ()
t2= ()
print(id(t), id(t2))
print(t==t2, t is t2)
O/P =
10105376 10105376
True True
140575063623864 140575063623864
True True
140575043621448 140575043613832
True False
140575063412808 140575063412808
True True
Program: 2. Membership operators:
NOte
We can use Membership operators to check
whether the given object present in the
given collection.(It may be String,List,Set,Tuple or
Dict)
in Returns True if the given object present in the
specified Collection
not in Retruns True if the given object not
present in the specified Collection
a='python'
print(a in 'p')
print('p' in a)
list = [2,'dog']
print(2 in list)
print( 4 not in list)
O/P =
False
True
True
True
Module:
Many way to declare module:-
1st way:
import module name
EX:
Import math
2nd way: Once we create alias name, by using that we can access functions
and variables of that
module
import math as m
3rd way:
- We can import a particular member of a module
explicitly as follows
from math import sqrt
- If we import a member explicitly then it is not
required to use module name while
accessing. If it will try to use module name then
will get error.
Program:
Note:
1- eval() can evaluate the Input to list, tuple, set,
etc based the provided Input.
2- Whatever input you will provide that will be
type of your variable.
l = eval(input('Enter value: '))
print (type(l))
print(l)
O/P =
Enter value: 12
<class 'int'>
12
Program:
l = eval(input('Enter value: '))
print (type(l))
print(l)
O/P =
Enter value: 'name'
<class 'str'>
name
Program:
l = eval(input('Enter value: '))
print (type(l))
print(l)
O/P=
Enter value: [2,'name',1.2]
<class 'list'>
[2, 'name', 1.2]
Program:
l = eval(input('Enter value: '))
print (type(l))
print(l)
O/P =
Enter value: (2+2)//2
<class 'int'>
Program:
l = eval(input('Enter value: '))
print (type(l))
print(l)
O/P =
Enter value: (2+2)/2
<class 'float'>
2.0
Program:
l = eval(input('Enter value: '))
print (type(l))
print(l)
O/P =
Enter value: 'name'+' '+'last_name'
<class 'str'>
name last_name
Program:
print(2*'name')
print('name'*3)
O/P=
namename
namenamename
Program: print(formatted string):
a =10
b = 12.2
c = 'Dog'
print('value of %i'%a);
print('value of %d'%a);
print('value of %f'%b)
print('value of %s'%c)
print('value of %i'%b)
O/P =
value of 10
value of 10
value of 12.200000
value of Dog
value of 12
Program:print() with replacement operator {}
a = 'good'
b = 'Dog'
print('This is a {0} bv {1}'.format(a,b))
O/P=
This is a good bv Dog
Program: Del function
Note: after delete the variable we can not access
that variable
n = 10
print(n);
del n;
print(n)
O/p =
10
Traceback (most recent call last):
File "[Link]", line 4, in <module>
print(n)
NameError: name 'n' is not defined
Note:
We can delete variables which are pointing to
immutable [Link] we cannot delete
the elements present inside immutable object.
Eg:
1) s="durga"
2) print(s)
3) del s==>valid
4) del s[0] ==>TypeError: 'str' object doesn't
support item deletion
Program: len() function to used find the no
character
a = 'combination';
print(len(a))
O/P =
11
Program: end is used to remove to go to next
cursor
a = 'combination';
for i in a:
print(i, end=' ')
O/P =
c o m b i n a t i o n
Program: removing space from string
Note:
1. rstrip()===>To remove spaces at right hand side
2. lstrip()===>To remove spaces at left hand side
3. strip() ==>To remove spaces both sides
name= input('Enter you name:')
name2 = input('Enter your name: ')
name = [Link]()
name2 = [Link]()
if(name == name2):
print('Yes nam is same ')
O/P =
Enter you name:sachin
Enter your name: sachin
Yes nam is same
Program: counting no of times character/string is
coming by count() function
Note:
1. [Link](substring) ==> It will search through out the string
2. [Link](substring, bEgin, end) ===> It will search from bEgin index to end-1 index
name= input('Enter you name:')
print([Link]('a'))
print([Link]('h',2,5))
O/P =
Enter you name:sachhhin
2
Program:
n = 'col'
change = [Link]('col','cool')
print(change)
print(id(n))
print(id(change))
n1 = 'abababab';
print([Link]('b','bc'))
O/P =
cool
139907787194072
139907786536640
abcabcabcabc
Program: Split() function
name = 'cool ,boy vdv'
n = [Link](',')
for i in n:
print(i)
O/P =
cool
boy vdv
Functions: multiple value pass across single return.
Program:
def fun(a,b):
v = a+b
w = a-b
return v, w;
x = fun(2,3)
print(x, type(x))
x,y = fun(5,5)
print(x,y)
print(x, type(x))
O/P =
(5, -1) <class 'tuple'>
10 0
10 <class 'int'>
Types of arguments :
There are 4 types are actual arguments are allowed in Python.
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments
Program: variable length argument.
def n_number(*n):
total = 0
for i in n:
total = total+i;
print(total);
n_number(10,20)
O/P =30
=> Variable
Program: Global variable.
Note: global variable can be call under any
function also and outside function
a= 10
def var():
print('inner a value:', a)
var()
print('outer a value:',a)
O/P:
inner a value: 10
outer a value: 10
Program:
Note if global variable and local variable are same
name then under function first prefer will give to
local variable.
a= 10
def var():
a=5
print('inner a value:', a)
var()
print('outer a value:',a)
O/p =
inner a value: 5
outer a value: 10
Program:
Note: if
a= 10
def var():
global a;
a=5
print('inner a value:', a)
var()
print('outer a value:',a)
Program:
Note: if you wanna access function variable to out
side the function so just declare global syntax.
a= 10
def var():
global a;
a=5
print('inner a value:', a)
var()
print('outer a value:',a)
O/P =
inner a value: 5
outer a value: 5
Program:
def var():
global a;
a=5
print('inner a value:', a)
def var1():
print('second function value:', a)
var()
var1()
print('outer a value:',a)
O/P =
inner a value: 5
second function value: 5
outer a value: 5
Program:
a =20;
def call_global():
a= 10;
print(globals()['a'])
call_global()
O/P =20
Program:
Note:
Anonymous Functions:
Sometimes we can declare a function without any name,such type of nameless
functions
are called anonymous functions or lambda functions.
The main purpose of anonymous function is just for instant use(i.e for one time
usage)
p = lambda p:p*p
print('value: ',p(4))
O/P =
value: 16
Function Aliasing:
For the existing function we can give another name, which is nothing but function aliasing.
Program:
def call(a,b):
c = a+b;
print(c)
call2 = call
call(10,20)
call2(15,24)
print(id(call))
print(id(call2))
O/P =
30
39
140342593051640
140342593051640
Program:
Note: If we delete one name still we can access that function by using alias name
def call(a,b):
c = a+b;
print(c)
call2 = call
call(10,20)
call2(15,24)
del call;
call2(10,10)
call(10,10)
O/P =
30
39
20
Traceback (most recent call last):
File "[Link]", line 11, in <module>
call(10,10)
NameError: name 'call' is not defined
Program:
for i in range(5,0,-1):
print(i)
for i in range(3,0,-1 ):
print('second: ',i)
for i in range(0,3, ):
print('third: ',i)
O/P =
4
second: 3
second: 2
second: 1
third: 0
third: 1
third: 2
Program:1
print('1.','sachin Gupta');
print('2.','Sachin \nGupta');
print('3.','Sachin \n Gupta');
print('4.','Sachin \n\tGupta');
O/p =
Gupta
3. Sachin
Gupta
4. Sachin
Gupta
Program:2
import sys
print('Print versi
on which you are using:- ',[Link]);
O/p =
Print version which you are using:- 3.4.3 (default, Nov 12 2018,
22:25:49)
[GCC 4.8.4]
Program:3
First_Name = input('Please Enter your name: ');
Last_Name = input('Please enter your last name: ');
print('Reverse name:-', Last_Name,First_Name);
O/P =
Please Enter your name: sachin
Please enter your last name: Gupta
Reverse name:- Gupta sachin
Program:4
Inputs = input('Please Enter your name:');
print('What is data type of Inputs variable',Inputs )
S = [Link]()
print('What is data type of S: ', type(S))
print(S)
O/P:
Please Enter your name:15 12 15
What is data type of Inputs variable <class 'str'>
What is data type of S: <class 'list'>
['15', '12', '15']
Please Enter your name:12,15,15
What is data type of Inputs variable <class 'str'>
What is data type of S: <class 'list'>
['12,15,15']
Program:
To build up understanding on Split() function.
Note: by default it is take space
Inputs = input('Please Enter your name:');
S = [Link]()
print('This is in the form of List',S);
print('This is converting into tuple data type',
tuple(S))
S = [Link]('.')
print(S)
O/P=
Please Enter your name:12.15.14
This is in the form of List ['12.15.14']
This is converting into tuple data type ('12.15.14',)
['12', '15', '14']
Please Enter your name:15 16 14
This is in the form of List ['15', '16', '14']
This is converting into tuple data type ('15', '16', '14')
['15 16 14']
Program:
Write a Python program which accepts a sequence of comma-separated
numbers from user and generate a list and a tuple with those numbers
Sample data : 3, 5, 7, 23
Output :
List : ['3', ' 5', ' 7', ' 23']
Tuple : ('3', ' 5', ' 7', ' 23')
Inputs = input('Please Enter your name:');
S = [Link]()
print('This is in the form of List',S);
print('This is converting into tuple data type',
tuple(S))
O/P=
Please Enter your name:12 10 14 58
This is in the form of List ['12', '10', '14', '58']
This is converting into tuple data type ('12', '10', '14', '58')
Program: Write a Python program to accept a filename from the user
and print the extension of that.
Sample filename : [Link]
Output : java
Inputs = input('Please Enter your name:');
S = [Link]('.')
print('This will give only extention name of any
file:- ',S[-1]);
Please Enter your name:[Link]
This will give only extention name of any file:- java
Please Enter your name:[Link]
This will give only extention name of any file:- mummy
Program: Write a Python program to display the first and last colors
from the following list.
color_list = ["Red","Green","White" ,"Black"]
Inputs = input('Please Enter your name:');
print('First element:- ',Inputs[0],'\nLast
element:-',Inputs[-1])
print('After split')
S = [Link]()
print('First element:- ',S[0],'\nLast element:-',S[-1])
O/P=
Please Enter your name:HI my name is java
First element:- H
Last element:- a
After split
First element:- HI
Last element:- java
Program:
Write a Python program that accepts an integer (n) and computes the
value of n+nn+nnn.
Sample value of n is 5
Expected Result : 615
a = int(input("Input an integer : "))
n1 = int( "%s" % a )
n2 = int( "%i%i" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
print(n1);
print(n2);
print(n3);
print (n1+n2+n3)
O/P=
Input an integer : 1
11
111
123
Program:
More than 2 parameter will not take at a time.
a = int(input("Input an integer : "))
n1 = int( a )
n3 = int( a,a,a )
print(n1);
print(n3);
O/P= Error
Input an integer : 5
Traceback (most recent call last):
File "[Link]", line 3, in <module>
n3 = int( a,a,a )
TypeError: int() takes at most 2 arguments (3 given)
Program: Write a Python program to print the calendar of a given
month and year.
Note : Use 'calendar' module.
import calendar
y = 2020
m=1
y = [Link](y, m)
print(y)
print([Link](2020, 2))
O/P=
January 2020
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
February 2020
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29
Program:
print(""" This is my 'PC'
Please check on somewhere """);
print('\n')
print(""" This is my 'PC'
Please check on somewhere """)
O/P =
This is my 'PC'
Please check on somewhere
This is my 'PC'
Please check on somewhere
Program:
import datetime
D1 = [Link](2020, 2, 1);
D2 = [Link](2019, 2, 1);
Final = D2-D1;
print(Final)
O/P =
-365 days, 0:00:00
OR:
from datetime import date
D1 = date(2020, 2, 1);
D2 = date(2019, 2, 1);
Final = D2-D1;
print(Final)
O/P =
-365 days, 0:00:00
Program:
Write a Python program to calculate the sum of three given numbers, if the
values are equal then return three times of their sum.
print(abs(-2))
O/P= 2
Program:
def Passing(x,y,z):
sum = x+y+z;
if x==y==z:
sum = sum*3
#print('All thre values are equal:',sum);
return sum
print(Passing(2,2,2))
O/P=
18
Program:
Note: Break can not be use with only if else
[Link] will use only with loop statement.
if a=10:
break:
O/P=
File "[Link]", line 1
if a=10:
SyntaxError: invalid syntax
Program:
def Check_String(s):
if s[:2]=="Is":
return s
print(Check_String("Isname"))
O/p= Isname
Program:
def to_change_list_to_str(list):
strp = '';
for name in list:
# strp = strp+str(name);
strp += str(name)
print(strp)
value = [1,2,25,22];
to_change_list_to_str(value)
O/P =
122522
Program: Write a Python program to print out a set containing all the
colors from color_list_1 which are not present in color_list_2.
est Data :
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
Expected Output :
{'Black', 'White'}
Note: Set have difference function to find out
different value, but list doesnt have to do this.
l1= set([1,2,3,4])
l2 = set([1,5,])
print([Link](l2))
O/p =
{2, 3, 4}