PYTHON
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
print( type(X) ) #<class 'int'>
print( type(Y) ) #<class 'float'>
print( type(Z) ) #<class
'complex'>
8
String Data Type
>>> 'University of Barisal' #Using Single quotation
'University of Barisal'
>>> "University ‘of’ Barisal" #Using Double quotation
“University ‘of’ Barisal”
>>> '''University of Barisal''' # Using Triple quotation.
'University of Barisal' # Used when single and
double -
# quote in the string.
# Also used for multi line comment 9
String Data Type
A = "Python Course"
print( A ) # 'Python Course'
print( type(A) ) # <class 'str'>
print( A[0] ) # ‘P’
print( A + “ basic” ) # Python Course basic
# In string + operator is used for strings concatenation.
10
Can you guess the output of the CODE?
X = "Python Course"
print( X * 2 )
# In string * operator is used for
repeatedly concat strings.
11
Can you guess the output of the CODE? (ans)
X = "Python Course"
print( X * 2 ) # It will print X two times
# ‘Python CoursePython 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?
Array is a data structure in CPP which can store only same
type data.
But in Python we can store multiple type data in a List.
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
}
print( X[Key1] ) # Value1
X[Key1] = NewValue
print( X[Key1] ) #NewValue
18
Dictionary Data Type (example)
student = {
‘name’ : “Tomal Saha”,
‘dept’ : “CSE”,
‘cgpa’ : 3.64,
2 : “test”
}
print( student[‘name’] ) # ‘Tomal
Saha’
print( student[2] ) #
‘Test’
# what happen if duplicate keys? 19
Dictionary Data Type (example-2)
# what happen if duplicate keys?
# It returns latest key-value.
student = {
2 : "test",
2 : "python"
}
print( student[2] ) # ‘Python’
student[2] = "java" # → assign new value
print( student[2] ) # ‘Java’
20
Dictionary Data Type (example-3)
student = { }
print( type(student) ) # <class
'dict'>
student[‘name’] = “Tomal Saha”
print( student[‘name’] ) # ‘Tomal
Saha’
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
print( type(Z) ) #<class
'float'>
NB: It’s called type Conversion (One kind of Type
Casting)
23
But… What is
TYPE CASTING
???
24
Type Casting in Python
Two types. Implicit Casting and Explicit Casting.
Implicit Casting: automatically converts object of one type into
other.
Explicit Casting: use Python's built-in functions to perform the
conversions. i.e. int(), str()
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
>>> a = int( 3.14 )
>>> a
3
>>> a = int (3.6 * 4)
>>> a → What will be the output?
28
Type Casting in Python (Explicit)
int() Function
>>> a = int( 3.14 )
>>> a
3
>>> a = int (3.6 * 4)
>>> a → What will be the output?
14 → cause: 3.6 * 4 = 14.4
29
Type Casting in Python (Explicit)
Binary String to Integer
>>> a = int( "110011", 2 )
>>> a
51
# Same thing can be done with Octal and
# Hexadecimal string. i.e.
>>> a = int("2A9", 16)
>>> a
681
30
Type Casting in Python (Explicit)
float() Function
>>> 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?
X = {1:100, 2:200, 3:300}
print( type(X) )
X = str(X)
print( X )
33
What is the output of the CODE? (ans)
X = {1:100, 2:200, 3:300}
print( type(X) ) # <class 'dict'>
X = str(X)
print( X ) #
‘{1:100, 2:200, 3:300}’
34
Conversion of Sequence Types
list(), tuple()
>>> a = [2, 3, 5]
>>> b = “cse”
>>> obj = list( b )
>>> obj
[‘c’, ‘s’, ‘e’]
>>> obj = tuple(a)
>>> obj
(2, 3, 5)
35
Exercise
Time
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.
Sample Input: “Binte Nur”
Sample Output: “Hello Binte Nur! Welcome to Python
Programming Course!”
Here, note that no
space before
exclamation (!) mark.
37
Exercise – 3.1 (ans)
name = input()
print("Hello", name+"!", "Welcome to Python Programming Course!")
name = input()
print("Hello", name+"!", "Welcome to Python
Programming Course!")
38
Exercise – 3.2 (theory)
str = “ a b c d e f ”
Index→ 0 1 2 3 4 5
str[ start : end ] → return substring of str from index start
to end-1.
str[ : idx ] → return substring of str from beginning to
index idx-1.
str[ idx : ] → return substring of str from index idx to end
of the string.
39
Exercise – 3.2 (theory)
str = “ a b c d e f”
Index→ 0 1 2 3 4 5
print( str[2:4] ) # ‘cd’
print( str[1:] ) # ‘abcdef’
print( str[:3] ) # ‘abc’
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.
Sample String : 'python'
Expected Result : 'pyon'
Sample String : 'do'
Expected Result : 'dodo'
Sample String : 'w'
Expected Result : ''
41
Exercise – 3.2 (ans type - 1)
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:]
print(string_both_ends('python')) # Output: 'pyon'
print(string_both_ends('do')) # Output: 'do'
print(string_both_ends('w')) # Output: ''
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
print(var > 3 and var < 10) True
print(var > 3 or var < 4) True
False
print(not (var > 3 and var < 10))
58
Membership Operators in Python
59
Membership Operators in Python
a = 10 OUTPUT
b = 5
list = [1, 2, 3, 4, 5 ]
a is not present in the given list
if ( a in list ):
print ("a is present in the given list")
b is present in the given list
else:
print ("a is not present in the given list")
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
The following table lists all
operators from highest
precedence to lowest.
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
Given a year, Find it is Yeap-Year or not.
Sample Input: 2000
Sample Output: “Leap Year”
Sample Input: 2023
Sample Output: “Not Leap Year”
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’
Sample Input: "01411111111"
Sample Output: “Banglalink” 71
Exercise – 3.7 (ans)
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
You are given 3 numbers. Find out the largest number.
Sample Input: 4 2 7
Sample Output: 7
Bonus-1: What if - you are given 5 numbers?
Bonus-2: What if - you are given 10 numbers?
73
Exercise – 3.8 (ans)
# a,b,c = map(int,input().split(" "))
a = int(input())
b = int(input())
c = int(input())
if(a>=b and a>=c):
print(a)
elif(b>=c):
print(b)
else:
print(c)
74
Exercise – 3.9
Write a Python program that accepts an integer (n) and
computes the value of n+nn+nnn.
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