Python - 03 and 04
Python - 03 and 04
Lecture - 03 and 04
1
R E C A P
2
What are the correct variable name in python?
Saturn
D current balance
It’s a gas giant and has several rings
_r
_ribnat A
Neptune
E total_$um
It’s the farthest planet from the Sun
Mars
‘Hello’
Despite being red, Mars is cold
B
Mercury
F 4Account
It’s the closest planet from the Sun
Earth
current_balance
Earth is the third planet from the Sun
C
3
What are the correct variable name in python?
Saturn
D current balance
It’s a gas giant and has several rings
_r
_ribnat A
Neptune
E total_$um
It’s the farthest planet from the Sun
Mars
‘Hello’
Despite being red, Mars is cold
B
Mercury
F 4Account
It’s the closest planet from the Sun
Earth
current_balance
Earth is the third planet from the Sun
C
4
5
Numeric Data Type
6
How to declare?
X = 100
Y = 3.1416
Z = 2 + 4j
print(X) #100
print(Y)
#3.1416
print(Z) #2+4j
7
type() Function in Python
It returns the DATA TYPE of a variable!
X = 100
Y = 3.1416
Z = 2 + 4j
A = "Python Course"
10
Can you guess the output of the CODE?
X = "Python Course"
print( X * 2 )
11
Can you guess the output of the CODE? (ans)
X = "Python Course"
12
List Data Type details
→ used [ ] for List.
→ It’s editable and elements can be any data-type.
X = [ 2, 5, 7, 11 ]
Y = [ 2, 3.1416, “CSE” ]
Z = [ 1, 2.5, 1+3j, [“Python”, “CPP”, “Java”] ]
print( X ) # [ 2, 5, 7, 11 ]
print( type(Y) ) # <class 'list'>
print( Z[0] ) #1
print( Z[3] ) # [“Python”, “CPP”,
“Java”] 13
What is the difference between
List in Python and Array in CPP?
14
What is the difference between
List in Python and Array in CPP?
15
Tuple Data Type
→Same as List. Square brackets replace with Parentheses.
→You can only access but can’t replace elements.
X = ( 2, 5, 7, 11 )
Y = ( 2, 3.1416, “CSE” )
Z = ( [“Python”, “CPP”, “Java”], (2, 3.5) )
print( X ) # ( 2, 5, 7, 11 )
print( type(Y) ) # <class 'tuple'>
print( Y[0] ) #2
print( Z[0] ) # [“Python”, “CPP”,
“Java”]
print( Z[1] ) # (2, 3.5) 16
Set Data Type
→Set uses Curly brackets.
→Set items are unordered, unchangeable, and don’t allow
duplicate values.
X = { 7, 2, 2, 7, 11 }
print( X ) # { 2, 7, 11 }
print( type(X) ) # <class 'set'>
print( X[0] ) # It gives Error
print( len(X) ) # 3 (It returns the length of the
set)
17
Dictionary Data Type
→Uses Curly brackets
→Inside curly brackets, used KEY : VALUE
→Key and Value can be any datatype.
X={
Key1 : Value1,
Key2 : Value2,
Key3 : Value3
}
student = {
‘name’ : “Tomal Saha”,
‘dept’ : “CSE”,
‘cgpa’ : 3.64,
2 : “test”
}
print( student[‘name’] ) # ‘Tomal
Saha’
print( student[2] ) #
‘Test’
student = {
2 : "test",
2 : "python"
}
print( student[2] ) # ‘Python’
student[2] = "java" # → assign new value
20
Dictionary Data Type (example-3)
student = { }
21
What is the output of the CODE?
X = 101
Y = 3.1416
Z=X+Y
print( type(Z) )
22
What is the output of the CODE? (answer)
X = 101
Y = 3.1416
Z=X+Y
24
Type Casting in Python
Two types. Implicit Casting and Explicit Casting.
25
Type Casting in Python (Implicit)
A = 10
B = 3.5
C = True
D=A+B
print( D, type(D) ) → output??
E=A+C
print( E, type(E) ) → output??
26
Type Casting in Python (Implicit)
A = 10
B = 3.5
C = True
D=A+B
print( D, type(D) ) → 13.5 <class 'float'>
E=A+C
print( E, type(E) ) → 11 <class 'int'>
27
Type Casting in Python (Explicit)
int() Function
28
Type Casting in Python (Explicit)
int() Function
29
Type Casting in Python (Explicit)
Binary String to Integer
>>> a = float(“3.14”)
>>> a
3.14
>>> b = float(15)
>>> b
15.0
31
Type Casting in Python (Explicit)
str() Function
>>> a = str(3.14)
>>> a
‘3.14’
>>> b = str(15)
>>> b
‘15’
>>> c = str(2/5)
>>> c
‘0.4’ 32
What is the output of the CODE?
print( type(X) )
X = str(X)
print( X )
33
What is the output of the CODE? (ans)
X = str(X)
print( X ) #
‘{1:100, 2:200, 3:300}’
34
Conversion of Sequence Types
list(), tuple()
>>> a = [2, 3, 5]
>>> b = “cse”
36
Exercise – 3.1
Take input a string as name from user and greetings
her/him to python programming course. For better
understanding see the input/output format.
37
Exercise – 3.1 (ans)
name = input()
print("Hello", name+"!", "Welcome to Python Programming Course!")
name = input()
38
Exercise – 3.2 (theory)
str = “ a b c d e f ”
Index→ 0 1 2 3 4 5
str = “ a b c d e f”
Index→ 0 1 2 3 4 5
40
Exercise – 3.2
Write a Python program to get a string made of the first 2
and last 2 characters of a given string. If the string length is
less than 2, return the empty string instead.
str = input()
if len(str) < 2:
print('')
print(str[0:2] + str[-2:])
42
Exercise – 3.2 (ans type - 2)
def string_both_ends(str):
if len(str) < 2:
return ''
return str[0:2] + str[-2:]
43
Exercise – 3.3
Create a dictionary named as Student with the following
Key-value:
Name →Take a string as student’s name
Roll →Take a string as student’s roll
Dept →Take a string as student’s department
Cgpa →Take a float value as student’s cgpa
Marks →Take another dictionary as student’s marks.
Which takes subject name(AI, DSA, MATH) as
key and it’s marks as key-value.
44
Exercise – 3.3 (ans)
Student = {
'Name': "Khan Rokib",
'Roll': "15CSE006",
'Dept': "CSE",
'Cgpa': 3.68,
'Marks': {
'AI': 81,
'DSA':82,
'MATH':83
}
}
print(Student['Name'], Student['Cgpa'])
print(Student['Marks'])
45
print(Student['Marks']['AI'])
Exercise – 3.4
You are given two positive numbers Num1 and Num2. Find
the ceil of (Num1 / Num2).
➔ Here Num1 isn’t multiple of Num2.
➔ ceil means rounds a number UP to the nearest integer,
if necessary.
➔ Don’t use direct ceil() function.
Sample Input: 10 3
Sample Output: 4
46
Exercise – 3.4 (ans)
a = int(input())
b = int(input())
ans = (a+b)/b
print(int(ans))
47
Python Operators
48
Arithmetic Operators in Python
49
Arithmetic Operators in Python
a = 5 OUTPUT
b = 3
c = a + b
print ("a: {} b: {} a+b: {}".format(a,b,c)) a: 5 b: 3 a+b: 8
c = a / b
a: 5 b: 3 a/b: 1.6666667
print ("a: {} b: {} a/b: {}".format(a,b,c))
c = a//b
a: 5 b: 3 a//b: 1
print ("a: {} b: {} a//b: {}".format(a,b,c))
c = a % b a: 5 b: 3 a%b: 2
print ("a: {} b: {} a%b: {}".format(a,b,c))
c = a**b a: 5 b: 3 a**b: 125
print ("a: {} b: {} a**b: {}".format(a,b,c))
50
Comparison Operators in Python
51
Comparison Operators in Python
a = 21 OUTPUT
b = 10
if ( a == b ):
print ("a is equal to b") a is not equal to b
else:
print ("a is not equal to b")
a is either less than or equal
to b
a,b = b,a #values of a and b swapped.
if ( a <= b ):
print ("a is either less than or equal to b")
else:
print ("a is neither less than nor equal to b")
52
Bitwise Operators in Python
53
Bitwise Operators in Python
a = 20 OUTPUT
b = 10
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = a & b; a= 20 : 0b10100 b= 10 : 0b1010
print ("AND is ", c,':',bin(c))
AND is 0 : 0b0
c = a | b;
OR is 30 : 0b11110
print ("OR is ", c,':',bin(c))
EXOR is 30 : 0b11110
c = a ^ b;
COMPLEMENT is -21 : -0b10101
print ("EXOR is ", c,':',bin(c))
c = ~a;
LEFT SHIFT is 80 : 0b1010000
print ("COMPLEMENT is ", c,':',bin(c))
RIGHT SHIFT is 5 : 0b101
c = a << 2;
print ("LEFT SHIFT is ", c,':',bin(c))
c = a >> 2;
54
print ("RIGHT SHIFT is ", c,':',bin(c))
Assignment Operators in Python
55
Assignment Operators in Python
a = 21 OUTPUT
b = 10
c = 0
c += a a: 21 c += a: 21
print ("a: {} c += a: {}".format(a,c)) a: 21 c *= a: 441
c *= a a: 21 c /= a : 21.0
print ("a: {} c *= a: {}".format(a,c)) a: 21 b: 10 c : 2
c /= a a: 21 c %= a: 2
print ("a: {} c /= a : {}".format(a,c))
c = 2
print ("a: {} b: {} c : {}".format(a,b,c))
c %= a
print ("a: {} c %= a: {}".format(a,c))
56
Logical Operators in Python
57
Logical Operators in Python
var = 5 OUTPUT
58
Membership Operators in Python
59
Membership Operators in Python
a = 10 OUTPUT
b = 5
list = [1, 2, 3, 4, 5 ]
if ( b not in list ):
print ("b is not present in the given list")
else:
print ("b is present in the given list")
60
Identity Operators in Python
61
Identity Operators in Python
a = [1, 2, 3, 4, 5] OUTPUT
b = [1, 2, 3, 4, 5]
c = a
True
False
print(a is c) False
print(a is b) True
print(a is not c)
print(a is not b)
62
Operators
Precedence
63
What is the output of the CODE?
X = 2<<2**2+1
print( X )
64
What is the output of the CODE? (answer)
X = 2<<2**2+1
print( X ) # 64
# 2 << 2 ** 2 + 1
# 3rd 1st 2nd
So,
2<<4+1
2<<5 →00000010 (2 in binary)
64 →01000000 (64, after 5 left
shift of 2) 65
EXERCISE
66
Exercise – 3.5
67
Exercise – 3.5 (ans)
year = int(input())
flag = 0 # 1 means leap year, otherwise 0
if year % 400 == 0:
flag = 1
elif year%100 != 0 and year%4 == 0:
flag = 1
if(flag):
print("Leap Year")
else:
print("Not Leap Year") 68
Exercise – 3.7
You are given a phone number as a string. Report as “INV”
if the number is invalid. Otherwise find out its operator
company name. Every valid number has exact 11 digits and
first 3 digits decide it’s operator company name. Here is the
list of valid operators & their codes:
Grameenphone → ‘017’ or ‘013’
Teletalk → ‘015’
Banglalink →’014’ or ‘019’
Airtel →’016’
Robi →’018’
num = input()
if(len(num)!=11):
print("INV")
elif(num[:3]=="017" or num[:3]=="013"):
print("Grameenphone")
elif(num[:3]=="014" or num[:3]=="019"):
print("Banglalink")
elif(num[:3]=="015"):
print("Teletalk")
elif(num[:3]=="016"):
print("Airtel")
elif(num[:3]=="018"):
print("Robi")
else:
print("INV") 72
Exercise – 3.8
Sample Input: 4 2 7
Sample Output: 7
73
Exercise – 3.8 (ans)
if n = 5
then, nn = 55
And, nnn = 555
Sample value of n is 5
Expected Result : 615
75
Exercise – 3.9 (ans)
a = input()
n1 = int(a)
n2 = int(a+a)
n3 = int(a+a+a)
print(n1 + n2 + n3)
76
Resources
● https://www.tutorialspoint.com/python/index.htm
● https://www.w3resource.com/python/python-tutorial.php
● https://www.w3resource.com/python-exercises/string/
● https://www.w3schools.com/python/
● https://www.geeksforgeeks.org/python-programming-
language/
● https://youtu.be/t2_Q2BRzeEE?si=OO6J_YNCZykedqsT
● https://realpython.com/
● Head First Python, 3rd Edition by Paul Barry
● Automate the Boring Stuff with Python By Al Sweigart.
77
Thank You
78