# Declaring and assigning value to constants
PI = 3.14
GRAVITY = 9.8
print(PI)
print(GRAVITY)
3.14
9.8
#Declaring and assigning value to a variable
a = "Apple"
print(a)
# Changing value of a variable
a = "Aeroplane"
print(a)
a = 100
print(a)
#Assigning Multiple values to a variable
b, c, d = 1, 2.5, "Hello"
print(b, c, d)
#Assigning same value to multiple variables
b = c = d = 6
print(b, c, d)
Apple
Aeroplane
100
1 2.5 Hello
6 6 6
class MyComplexNumber:
# Constructor methods
def __init__(self, real=0, imag=0):
print("MyComplexNumber constructor executing...")
self.real_part = real
self.imag_part = imag
def displayComplex(self): print("{0} + {1}j".format(self.real_part, self.imag_part))
# Create a new object against MyComplexNumber class
cmp1x1 = MyComplexNumber(20, 80)
# Calling displayComplex() function
#Output: 40 + 50j
cmp1x1.displayComplex()
MyComplexNumber constructor executing...
20 + 80j
# Create another object against MyComplexNumber class
# and create a new attribute 'new_attribute'
cmp1x2 = MyComplexNumber(60, 70)
cmp1x2.new_attribute = 80
cmp1x2.displayComplex()
#Output: (60, 70, 80)
print((cmp1x2.real_part, cmp1x2.imag_part, cmp1x2.new_attribute))
MyComplexNumber constructor executing...
60 + 70j
(60, 70, 80)
# but cmp1x1 object doesn't have attribute 'new_attribute' # AttributeError: 'MyComplexNumber' object has no attribute 'new_attribute'
# cmp1x1.new_attribute
# print(cmp1x1)
# Deleting object attributes and the object
print(cmp1x1)
del cmp1x1.real_part
del cmp1x1
<__main__.MyComplexNumber object at 0x7f3a35ea2630>
# print(cmp1x1) # output NameError: name 'cmp1x1' is not defined
# Defining and declaring and array
arr = [10, 20, 30, 40, 50]
print(arr)
#Accessing Array elements
print(arr[0])
print(arr[1])
print(arr[2])
print(arr[-1]) # Negative Indexing
print(arr[-2]) # Negative Indexing
[10, 20, 30, 40, 50]
10
20
30
50
40
brands = ["Tesla", "Apple", "Google", "Microsoft", "Toyota"]
print(brands)
# Finding the Length of the array
num_brands = len(brands)
print(num_brands)
# Adding an element to an array using append()
brands.append("Intel")
print(brands)
['Tesla', 'Apple', 'Google', 'Microsoft', 'Toyota']
5
['Tesla', 'Apple', 'Google', 'Microsoft', 'Toyota', 'Intel']
#Removing elements from an array
colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
print(colors)
del colors[4]
print(colors)
colors.remove("blue")
print(colors)
colors.pop(3)
print(colors)
['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
['violet', 'indigo', 'blue', 'green', 'orange', 'red']
['violet', 'indigo', 'green', 'orange', 'red']
['violet', 'indigo', 'green', 'red']
# Modifying elements of an array using indexing
fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
print(fruits)
fruits[1] = "Pineapple"
print(fruits)
fruits[-1] = "Guava"
print(fruits)
['Apple', 'Banana', 'Mango', 'Grapes', 'Orange']
['Apple', 'Pineapple', 'Mango', 'Grapes', 'Orange']
['Apple', 'Pineapple', 'Mango', 'Grapes', 'Guava']
# Concatenating two arrays using the + operator
concat = [1, 2, 3]
print(concat)
concat + [4, 5, 6]
print(concat)
concat += [4, 5, 6]
print(concat)
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4, 5, 6]
# Repeating element in an array
repeat = ["a"]
print(repeat)
repeat *= 5
print(repeat)
['a']
['a', 'a', 'a', 'a', 'a']
#Slicing an array
fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
print(fruits)
print(fruits[1:4])
print(fruits[:3])
print(fruits[-4:])
print(fruits[-3:-1])
['Apple', 'Banana', 'Mango', 'Grapes', 'Orange']
['Banana', 'Mango', 'Grapes']
['Apple', 'Banana', 'Mango']
['Banana', 'Mango', 'Grapes', 'Orange']
['Mango', 'Grapes']
# Declaring and defining multidimensional array
mult_d_arr = [[1, 2], [3, 4], [5, 6], [7, 8]]
print(mult_d_arr)
print(mult_d_arr[0])
print(mult_d_arr[3])
print(mult_d_arr[2][1])
print(mult_d_arr[3][0])
[[1, 2], [3, 4], [5, 6], [7, 8]]
[1, 2]
[7, 8]
6
7
File methods#
Keywords and identifiers#
# True False
print(5 == 5)
print(5 > 5)
True
False
# None
print(None == 0)
print(None == False)
print(None == [])
print(None == None)
False
False
False
True
def a_void_function():
a = 1
b = 2
c = a + b
# return c
x = a_void_function()
print(x)
None
# and, or, not
print(True and False)
print(True or False)
print(not False)
print(True and True)
print(True or True)
print(not True)
False
True
True
True
True
False
# as
import math as my_math
print(my_math.cos(my_math.pi))
-1.0
# assertion
# assert 5 > 5 # output AssertionError
assert 5 == 5
# break
for i in range(1, 11):
if i == 5:
break
print(i)
1
2
3
4
# continue
for i in range(1, 8):
if i == 5:
continue
print(i)
1
2
3
4
6
7
# class
class ExampleClass:
def function1(parameters):
print("function1() executing...")
def function2(parameters):
print("function2() executing...")
ob1 = ExampleClass()
ob1.function1()
ob1.function2()
function1() executing...
function2() executing...
# def
def function_name(parameters):
pass
function_name(10)
# del
a = 10
print(a)
del a
# print(a) # name 'a' is not defined
10
# if..elif..else
num = 2
if num == 1:
print('One')
elif num == 2:
print('Two')
else:
print('Something else')
Two
# try...raise...catch...finally
try:
X = 9
#raise ZeroDivisionError # Division cannot be performed #Execution Successfully
except ZeroDivisionError:
print("Division cannot be performed")
finally:
print("Execution Successfully") # Execution Successfully
Execution Successfully
# for
for i in range(1, 10, 1):
print(i)
1
2
3
4
5
6
7
8
9
# from.. import
from math import cos
print(cos(10))
-0.8390715290764524
#global
globvar = 10
def read1():
print(globvar)
def write1():
global globvar
globvar = 5
def write2():
globvar = 15
read1()
write1()
read1()
write2()
read1()
10
5
5
# in
a = [1, 2, 3, 4]
print(4 in a)
print(44 not in a)
True
True
# is
print(True is True)
True
# lambda
a = lambda x: x * 2
for i in range(1, 6):
print(i, a(i))
1 2
2 4
3 6
4 8
5 10
# nonLocal
a = 300
def outer_function():
a = 5
def inner_function():
nonlocal a # looks inside the outer scope not the global scope
a = 10
print("Inner function: ", a)
inner_function()
print('calling inner_function() a has been changed to', a)
print("Outer function: ", a)
outer_function()
Inner function: 10
calling inner_function() a has been changed to 10
Outer function: 10
# pass
def function(args):
pass
function(10)
# return
def func_return():
return True, 10
flag, number = func_return()
print(func_return())
print(flag)
print(number)
(True, 10)
True
10
#while
i = 5
while (i > 0):
print(i)
i -= 1
5
4
3
2
1
# with
with open('./example.txt', 'w') as my_file:
my_file.write('Hello world!')
# yield
def generator():
for i in range(6):
yield i * i
g = generator()
print(list(generator()))
for i in g:
print(i)
[0, 1, 4, 9, 16, 25]
0
1
4
9
16
25
Tuples#
# creating an empty tuple
tuple1 = ()
print(tuple1)
# creating tuples with integer elements print(tuple2)
tuple2 = (1, 2, 3)
print(tuple2)
#tuple with mixed datatypes
tuple3 = (101, "Anirban", 20000.00, "HR Dept")
print(tuple3)
()
(1, 2, 3)
(101, 'Anirban', 20000.0, 'HR Dept')
# creation of nested tuple
tuple4 = ("points", [1, 4, 3], (7, 8, 6))
print(tuple4)
# tuple can be created without any parentheses
# also called tuple packing
tuple5 = 101, "Anirban", 20000.00, "HR Dept"
print(tuple5)
# tuple unpacking is also possible
empid, empname, empsal, empdept = tuple5
print(empid)
print(empname)
print(empsal)
print(empdept)
print(type(tuple5))
('points', [1, 4, 3], (7, 8, 6))
(101, 'Anirban', 20000.0, 'HR Dept')
101
Anirban
20000.0
HR Dept
<class 'tuple'>
# accessing elements in a tuple
tuple1 = ('w', 'e', '1', 'c', 'o', 'm', 'e')
print(tuple1)
print(tuple1[1])
print(tuple1[3])
print(tuple1[5])
('w', 'e', '1', 'c', 'o', 'm', 'e')
e
c
m
# nested tuple
nest_tuple2 = ("point", [1, 3, 4], (8, 7, 9))
print(nest_tuple2)
print(nest_tuple2[0][3])
print(nest_tuple2[1][2])
print(nest_tuple2[2][2])
('point', [1, 3, 4], (8, 7, 9))
n
4
9
# slicing tuple contents
tuple1 = ('w', 'e', '1', 'c', 'o', 'm', 'e')
print(tuple1[1:3])
print(tuple1[:-3])
print(tuple1[3:])
print(tuple1[:])
('e', '1')
('w', 'e', '1', 'c')
('c', 'o', 'm', 'e')
('w', 'e', '1', 'c', 'o', 'm', 'e')
# tuple elements are immutable
tuple1 = ('w', 'e', '1', 'c', 'b', 'm', 'e')
print(tuple1)
# tuple1[2] = 'x' # error # 'tuple' object does not support item assignment
# tuples can be reassigned
tuple1 = ('g', 'o', 'o', 'd', 'b', 'y', 'e')
print(tuple1)
('w', 'e', '1', 'c', 'b', 'm', 'e')
('g', 'o', 'o', 'd', 'b', 'y', 'e')
# concatenation of tuples
tuple2 = ('w', 'e', '1')
tuple3 = ('c', 'o', 'm', 'e')
print(tuple2)
print(tuple3)
print(tuple2 + tuple3)
print(("again",) * 4)
('w', 'e', '1')
('c', 'o', 'm', 'e')
('w', 'e', '1', 'c', 'o', 'm', 'e')
('again', 'again', 'again', 'again')
# deletion operation on a tuple
tuple4 = ('w', 'e', '1', 'c', 'o', 'm', 'e')
# as immutable so elements can not be deleted
# del tuple4[2] # 'tuple' object doesn't support item deletion
# but can delete entire tuple
del tuple4
# print(tuple4) # name 'tuple4' is not defined
#tuple methods
tuple5 = ('w', 'e', '1', 'c', 'o', 'm', 'e')
print(tuple5.count('e'))
print(tuple5.index('c'))
2
3
# tuple operations
tuple6 = ('w', 'e', '1', 'c', 'o', 'm', 'e')
print(tuple6)
# membership
print('c' in tuple6)
print('c' not in tuple6)
print('a' in tuple6)
print('a' not in tuple6)
('w', 'e', '1', 'c', 'o', 'm', 'e')
True
False
False
True
# iteration through tuple elements
tuple6 = ('w', 'e', '1', 'c', 'o', 'm', 'e')
for letters in tuple6:
print("letter is -> ", letters)
letter is -> w
letter is -> e
letter is -> 1
letter is -> c
letter is -> o
letter is -> m
letter is -> e
# built-in functions with tuple
tuple7 = (22, 33, 55, 44, 77, 66, 11)
print(tuple7)
print(max(tuple7))
print(min(tuple7))
print(sorted(tuple7))
print(len(tuple7))
(22, 33, 55, 44, 77, 66, 11)
77
11
[11, 22, 33, 44, 55, 66, 77]
7
sets#
# creating sets
# sets of integers
my_set1 = {11, 33, 66, 55, 44, 22}
print(my_set1)
# set of mixed datatypes
my_set2 = {101, "Agnibha", (21, 2, 1994)}
print(my_set2)
# duplicate values are not allowed
my_set3 = {11, 22, 33, 33, 44, 22}
print(my_set3)
{33, 66, 22, 55, 11, 44}
{'Agnibha', (21, 2, 1994), 101}
{33, 11, 44, 22}
# set cannot have mutable items
# my_set4 = {1, 2, [3, 4]} # Error #unhashable type: 'list'
# we can make set from a list
my_set5 = set([1, 2, 3, 2])
print(type(my_set5))
print(my_set5)
# we can make list from a set
my_list1 = list({11, 22, 33, 44})
print(type(my_list1))
print(my_list1)
<class 'set'>
{1, 2, 3}
<class 'list'>
[33, 11, 44, 22]
# operations on sets
my_set1 = {11, 33, 44, 66, 55}
print(my_set1)
# 'set' object does not support indexing
#my_set1[0] #Error
# add an element
my_set1.add(77)
print(my_set1)
# add multiple elements
my_set1.update([88, 99, 22])
print(my_set1)
# add List and set
my_set1.update([100, 102], {103, 104, 105})
print(my_set1)
{33, 66, 55, 11, 44}
{33, 66, 55, 11, 44, 77}
{66, 11, 77, 22, 88, 33, 99, 44, 55}
{66, 11, 77, 22, 88, 33, 99, 100, 102, 103, 104, 105, 44, 55}
# remove and discard
# #initialize my_set
my_set1 = {11, 33, 44, 55, 66}
print(my_set1)
# discard an element which is not present, no error
my_set1.discard(4)
print(my_set1)
# remove an element which is not present, error raised
#my_set1.remove(6) # KeyError: 6
print(my_set1)
# discard an element
my_set1.discard(44)
print(my_set1)
my_set1.remove(55)
print(my_set1)
{33, 66, 55, 11, 44}
{33, 66, 55, 11, 44}
{33, 66, 55, 11, 44}
{33, 66, 55, 11}
{33, 66, 11}
# using pop()
#initialize my_set
my_set1 = {11, 33, 44, 55, 66}
print(my_set1)
# pop an element
print(my_set1.pop())
# pop another element
print(my_set1.pop())
print(my_set1)
# clear my_set
my_set1.clear()
print(my_set1)
{33, 66, 55, 11, 44}
33
66
{55, 11, 44}
set()
# set operations - union
myset1 = {0, 1, 2, 3, 4, 5}
myset2 = {4, 5, 6, 7, 8, 9}
print(myset1)
print(myset2)
# use | operator for union
print(myset1 | myset2)
print(myset2 | myset1)
print(myset1.union(myset2))
print(myset2.union(myset1))
{0, 1, 2, 3, 4, 5}
{4, 5, 6, 7, 8, 9}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
# set operations intersection
myset1 = {0, 1, 2, 3, 4, 5}
myset2 = {4, 5, 6, 7, 8, 9}
print(myset1)
print(myset2)
# use & operator for intersection
print(myset1 & myset2)
print(myset2 & myset1)
print(myset1.intersection(myset2))
print(myset2.intersection(myset1))
{0, 1, 2, 3, 4, 5}
{4, 5, 6, 7, 8, 9}
{4, 5}
{4, 5}
{4, 5}
{4, 5}
# set operations - set difference
myset1 = {0, 1, 2, 3, 4, 5}
myset2 = {4, 5, 6, 7, 8, 9}
print(myset1)
print(myset2)
#use - operator for set difference
print(myset1 - myset2)
print(myset2 - myset1)
print(myset1.difference(myset2)) # differences in only one set
print(myset2.difference(myset1))
# set operations symmetric difference
myset1 = {0, 1, 2, 3, 4, 5}
myset2 = {4, 5, 6, 7, 8, 9}
print(myset1)
print(myset2)
# use operator for symmetric difference
print(myset1 ^ myset2)
print(myset2 ^ myset1)
print(myset1.symmetric_difference(myset2)) # differences in all two sets
print(myset2.symmetric_difference(myset1))
{0, 1, 2, 3, 4, 5}
{4, 5, 6, 7, 8, 9}
{0, 1, 2, 3}
{8, 9, 6, 7}
{0, 1, 2, 3}
{8, 9, 6, 7}
{0, 1, 2, 3, 4, 5}
{4, 5, 6, 7, 8, 9}
{0, 1, 2, 3, 6, 7, 8, 9}
{0, 1, 2, 3, 6, 7, 8, 9}
{0, 1, 2, 3, 6, 7, 8, 9}
{0, 1, 2, 3, 6, 7, 8, 9}
# set membership
myset1 = {0, 1, 2, 3, 4, 5}
print(2 in myset1)
print(6 in myset1)
print(2 not in myset1)
print(6 not in myset1)
True
False
False
True
# iterating through a set
for letter in set("welcome"):
print(letter)
l
c
o
m
e
w
# built-in functions with set
myset1 = {0, 1, 2, 3, 4, 5}
print(len(myset1))
print(max(myset1))
print(min(myset1))
print(sorted(myset1))
6
5
0
[0, 1, 2, 3, 4, 5]
# python frozenset
# Frozenset is a new class that has the characteristics
# of a set, but its elements cannot be changed once assigned
# While tuples are immutable lists, frozen-sets are immutable sets.
# #initialize A and B
myset1 = frozenset([1, 2, 3, 4])
myset2 = frozenset([3, 4, 5, 6])
print(myset1)
print(myset2)
print(myset1.difference(myset2))
print(myset1.union(myset2))
print(myset1.intersection(myset2))
print(myset1.symmetric_difference(myset2))
# myset1.add(10) #'frozenset' object has no attribute 'add'
# it has look like tuples immutable
frozenset({1, 2, 3, 4})
frozenset({3, 4, 5, 6})
frozenset({1, 2})
frozenset({1, 2, 3, 4, 5, 6})
frozenset({3, 4})
frozenset({1, 2, 5, 6})
imports#
# Importing module as well as renaming it.
import math as m
print("The value of pi is", m.pi)
The value of pi is 3.141592653589793
# Usage of from
from math import pi
print("The value of pi is", pi)
The value of pi is 3.141592653589793
# import all names from the standard module math
from math import *
print("The value of pi is", pi)
The value of pi is 3.141592653589793
directories#
import os
print(os.getcwd()) #Returns the present working directory
print(os.getcwdb()) #Returns the present working directory as a byte object
/home/runner/work/python-revision/python-revision
b'/home/runner/work/python-revision/python-revision'
# os.chdir('C:\\Users\\Abdelrahman\\FileTest') #use to change directory
os.chdir('/Users/abdelrahman/PycharmProjects/python-revision/images') #use to change directory
print(os.listdir()) # ALL files and subdirectories inside a directory # can be known using the Listdir() method.
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[70], line 2
1 # os.chdir('C:\\Users\\Abdelrahman\\FileTest') #use to change directory
----> 2 os.chdir('/Users/abdelrahman/PycharmProjects/python-revision/images') #use to change directory
3 print(os.listdir()) # ALL files and subdirectories inside a directory # can be known using the Listdir() method.
FileNotFoundError: [Errno 2] No such file or directory: '/Users/abdelrahman/PycharmProjects/python-revision/images'
# os.mkdir('Test') # used to make a new directory
# os.rename('Test', 'New_One') # used to rename a directory
os.chdir('/Users/abdelrahman/PycharmProjects/python-revision/')
os.remove('example.txt') # use to remove a file
# os.rmdir('New_One') # use to remove a directory
# os.chdir('C:\\Users\\Abdelrahman')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[72], line 1
----> 1 os.chdir('/Users/abdelrahman/PycharmProjects/python-revision/')
2 os.remove('example.txt') # use to remove a file
3 # os.rmdir('New_One') # use to remove a directory
4 # os.chdir('C:\\Users\\Abdelrahman')
FileNotFoundError: [Errno 2] No such file or directory: '/Users/abdelrahman/PycharmProjects/python-revision/'
dictionary#
#Accessing elements from a dictionary
new_dict = {1: "Hello", 2: "Hi", 3: "Hola"}
print(new_dict)
print(new_dict[1]) # if invalid key rais error
print(new_dict.get(2)) # if invalid key return None
#Updating value
new_dict[1] = "Hey"
print(new_dict)
#Adding value
new_dict[4] = "Namaste"
print(new_dict)
{1: 'Hello', 2: 'Hi', 3: 'Hola'}
Hello
Hi
{1: 'Hey', 2: 'Hi', 3: 'Hola'}
{1: 'Hey', 2: 'Hi', 3: 'Hola', 4: 'Namaste'}
# Creating a new dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares)
# remove a particular item
print(squares.pop(4))
print(squares)
# remove an arbitrary item
print(squares.popitem())
print(squares)
# delete a particular item
del squares[1]
print(squares)
del squares # delete all dict
# print(squares) # Error # name 'squares' is not defined
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{2: 4, 3: 9}
# Creating a new dictionary using Comprehension
squares = {x: x * x for x in range(6)}
print(squares)
# Dictionary Membership test
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(squares)
print(1 in squares)
print(2 not in squares)
#membership tests for key only not value
print(49 in squares)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
True
True
False
# Iterating through a dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
# Using built-in functions in a dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(len(squares)) # Prints the Length of the dictionary
print(sorted(squares)) # Prints the dictionary in sorted order
1
9
25
49
81
5
[1, 3, 5, 7, 9]
Strings#
# different ways to define a string in Python
mystr1 = 'Welcome'
print(mystr1)
mystr2 = "Welcome"
print(mystr2)
mystr3 = '''Welcome'''
print(mystr3)
# triple quotes string can extend multiple lines
mystr3 = """Welcome
to the world of
Python Programming"""
print(mystr3)
Welcome
Welcome
Welcome
Welcome
to the world of
Python Programming
print(mystr3)
# accessing characters in a string
mystr = 'language'
print('mystr = ', mystr)
print('mystr[0] = ', mystr[0])
print('mystr[7] = ', mystr[7])
print('mystr[-1] = ', mystr[-1])
print('mystr[1:5] = ', mystr[1:5])
print('mystr[5:-2] = ', mystr[5:-2])
#print('mystr[10] = ', mystr[10]) # Error #string index out of range
Welcome
to the world of
Python Programming
mystr = language
mystr[0] = l
mystr[7] = e
mystr[-1] = e
mystr[1:5] = angu
mystr[5:-2] = a
# strings are immutable
# but different strings can be assigned
mystr = 'language'
print(mystr)
mystr = 'programming'
print(mystr)
#mystr[3] = 'x' #Error #'str' object does not support item assignment
language
programming
#concatenation of strings
mystr1 = 'Welcome'
mystr2 = ' to all'
# using + operator
print('mystr1 + mystr2 = ', mystr1 + mystr2)
# using * operator
print('mystr1 * 3 =', mystr1 * 3)
mystr1 + mystr2 = Welcome to all
mystr1 * 3 = WelcomeWelcomeWelcome
# iterating through a string
letter_count = 0
for letters in 'Hello World':
if (letters == 'l'):
letter_count += 1
print(letter_count, 'times 1 letter has been found')
3 times 1 letter has been found
# string membership
print('1' in "hello")
print('1' not in "hello")
print('b' in "hello")
print('b' not in "hello")
False
True
False
True
# built-in functions
mystr = 'university'
# using enumerate()
my_list_enumerate = list(enumerate(mystr))
print('list (enumerate (mystr)', my_list_enumerate)
#using character count
print('len (mystr) = ', len(mystr))
list (enumerate (mystr) [(0, 'u'), (1, 'n'), (2, 'i'), (3, 'v'), (4, 'e'), (5, 'r'), (6, 's'), (7, 'i'), (8, 't'), (9, 'y')]
len (mystr) = 10
# string formatting using escape sequence
#print("tell me "What's your name?"") # Error # SyntaxError
#using triple quotes
print('''tell me "What's your name?"''')
# escaping single quotes
print('tell me "What\'s your name?"')
# escaping single quotes
print("tell me 'What\'s your name?'")
#escaping double quotes
print("tell me \"What's your name?\"")
tell me "What's your name?"
tell me "What's your name?"
tell me 'What's your name?'
tell me "What's your name?"
print("C:\\User\\user\\mydata.txt")
print("this line is having a new line \ncharacter")
print("this line is having a tab \t character")
print("ABC written in \x41\x42\x43 (HEX) representation")
#format() method
# default (implicit) order
default_order = "{} {} and {}".format('Today', 'is', 'Sunday')
print(default_order)
# order using positional argument
positional_order = "{1} {0} and {2}".format('is', 'Today', 'Sunday')
print(positional_order)
# order using keyword argument
keyword_order = "{t} {i} and {s}".format(i='is', t='Today', s='Sunday')
print(keyword_order)
C:\User\user\mydata.txt
this line is having a new line
character
this line is having a tab character
ABC written in ABC (HEX) representation
Today is and Sunday
Today is and Sunday
Today is and Sunday
# formatting numbers
print("Required binary representation of {0} is {0:b}".format(20))
#formatting floats
print("Exponent representation: {0:e}".format(1566.345))
# round off
print("One third is: {0:.3f}".format(1 / 3))
Required binary representation of 20 is 10100
Exponent representation: 1.566345e+03
One third is: 0.333
# string methods
print("gOOD moRNing tO a1L".lower())
print("gOOD moRNing tO a1L".upper())
print("gOOD moRNing tO a1L".find('tO'))
print("gOOD moRNing tO a1L".find('to'))
print("gOOD moRNing tO a1L".replace('all', 'everybody'))
print("gOOD moRNing tO a1L".replace('a1L', 'everybody'))
good morning to a1l
GOOD MORNING TO A1L
13
-1
gOOD moRNing tO a1L
gOOD moRNing tO everybody
DataType Conversion#
# Implicit Type Conversion
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int: ", type(num_int))
print("datatype of num_flo: ", type(num_flo))
print("Value of num_new: ", num_new)
print("datatype of num_new: ", type(num_new))
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
# Addition of string (higher) data type and integer (Lower) datatype
num_int = 123
num_str = "456"
print("Data type of num_int: ", type(num_int))
print("Data type of num_str:", type(num_str))
# print(num_int+num_str) #Error: Implicit conversion will not work here
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
#Explicit Type Conversion
num_int = 123
num_str = "456"
print("Data type of num_int: ", type(num_int))
print("Data type of num_str before Type Casting: ", type(num_str))
num_str = int(num_str) # Converting string to int
print("Data type of num_str after Type Casting: ", type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:", num_sum)
print("Data type of the sum: ", type(num_sum))
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
Numbers#
value1 = 100
print(type(value1))
print(isinstance(value1, int))
print(isinstance(value1, float))
print(isinstance(value1, complex))
<class 'int'>
True
False
False
value2 = 100.24
print(type(value2))
print(isinstance(value2, int))
print(isinstance(value2, float))
print(isinstance(value2, complex))
<class 'float'>
False
True
False
value3 = 50 + 6j
print(type(value3))
print(isinstance(value3, int))
print(isinstance(value3, float))
print(isinstance(value3, complex))
<class 'complex'>
False
False
True
print(0b1101)
print(0xab)
print(0o23)
13
171
19
print(10 + 33.4)
43.4
# Type conversion
print(int(10.5))
print(int(-20.99))
print(float(10))
10
-20
10.0
#Python Decimal
from decimal import Decimal as D
data1 = 0.1 + 0.2
print(f"with normal way: {data1}")
print(f"with Decimal: {D('0.1') + D('0.2')}")
data1 = 1.20 * 2.50
print(f"with normal way: {data1}")
print(f"with Decimal: {D('1.2') * D('2.5')}")
with normal way: 0.30000000000000004
with Decimal: 0.3
with normal way: 3.0
with Decimal: 3.00
# Python Fractions
from fractions import Fraction as F
print(F(1.5))
print(F(5))
print(F(1, 5))
print(F(3, 70))
3/2
5
1/5
3/70
# Python math module
import math
print(math.pi)
print(math.cos(10))
print(math.log(10))
print(math.log10(10))
print(math.exp(10))
print(math.factorial(5))
print(math.sinh(10))
print(abs(-12.34))
3.141592653589793
-0.8390715290764524
2.302585092994046
1.0
22026.465794806718
120
11013.232874703393
12.34
# Python random module
import random
print('Random number -> ', random.randrange(5, 15))
print('Random number -> ', random.randrange(5, 15))
print('Random number -> ', random.randrange(5, 15))
print('Random number -> ', random.randrange(5, 15))
day = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
print(random.choice(day))
print(day)
random.shuffle(day)
print(day)
# Print random element
print(random.random())
Random number -> 6
Random number -> 9
Random number -> 7
Random number -> 14
Wed
['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
['Thu', 'Sat', 'Wed', 'Mon', 'Fri', 'Sun', 'Tue']
0.7654848496662885
Namespace#
# Name (also called identifier) is simply a name given to objects.
# We can get the address (in RAM) of some object through the built-in function, id(). #Note: You may get different value of id
a = 2
# Output: id (2)= 4363189832
print('id(2)=', id(2))
#Output: id (a) = 4363189832
print('id(a)=', id(a))
a = 2
# Output: id (a) = 4363189832
print('id(a)=', id(a))
a = a + 1
#Output: id(a) = 4363189864
print('id(a)=', id(a))
#Output: id(3) = 4363189864
print('id(3)=', id(3))
b = 2
#Output: id(2) = 4363189832
print('id(2)=', id(2))
print('id(b)=', id(b))
id(2)= 24222776
id(a)= 24222776
id(a)= 24222776
id(a)= 24222808
id(3)= 24222808
id(2)= 24222776
id(b)= 24222776
#Scope
def outer_function():
global a
a = 20
def inner_function():
global a
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
print('a =', a)
outer_function()
print('a =', a)
a = 10
a = 30
a = 30
a = 30
def outer_function():
a = 20
def inner_function():
global a
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
print('a =', a)
outer_function()
print('a =', a)
a = 10
a = 30
a = 20
a = 30
Local && Global and Nonlocal Variables#
# Global and Local variable with different name
x = "global" # Global variable can be accessed from anywhere
def funct1():
global x
y = "local"
x = x * 2
print(x)
print(y)
print("Global x = ", x)
funct1()
print("Global x = ", x)
Global x = global
globalglobal
local
Global x = globalglobal
# Global and Local variable with same name
a = 5
def funct2():
a = 10 # Local variables are accessed from the block where it is defined only
print("local a:", a)
print("global a:", a)
funct2()
print("global a:", a)
global a: 5
local a: 10
global a: 5
# Creating and using a Non-Local variable
def outer():
x = "local"
def inner():
nonlocal x # Nonlocal variable are used in nested function
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x) # This will print 'nonlocal' also
outer()
inner: nonlocal
outer: nonlocal
def outer_function():
a = 20
def inner_function():
a = 30
print('a =', a)
inner_function()
print('a =', a)
outer_function()
a = 30
a = 20
def outer_function():
a = 20
def inner_function():
nonlocal a
a = 30
print('a =', a)
inner_function()
print('a =', a)
outer_function()
a = 30
a = 30
b = 10
c = 100
def outer_function2():
b = 20
c = 300
def inner_function():
global b
print('changing global b value', b)
b = 3028932846923
nonlocal c
print('changing nonlocal c value', c)
c = 5050505
print('b =', b)
print('c =', c)
print('before calling inner_function b=', b)
print('before calling inner_function c=', c)
inner_function()
print('after calling inner_function b=', b)
print('after calling inner_function c=', c)
outer_function2()
print('b =', b)
print('c =', c)
before calling inner_function b= 20
before calling inner_function c= 300
changing global b value 10
changing nonlocal c value 300
b = 3028932846923
c = 5050505
after calling inner_function b= 20
after calling inner_function c= 5050505
b = 3028932846923
c = 100
Global variables#
def funct1():
x = 20
def funct2():
global x
# Global keyword is used to modify a global variable
x = 25
print("Before calling funct2: ", x)
print("Calling funct2 now")
funct2()
print("After calling funct2: ", x)
funct1()
print("x in main : ", x)
Before calling funct2: 20
Calling funct2 now
After calling funct2: 20
x in main : 25
Iterators#
#defining a list
our_list = [44, 77, 11, 33]
# get an iterator using iter() method
our_iter = iter(our_list)
## iterate through it using next() method
# prints 44
print(next(our_iter))
# prints 77
print(next(our_iter))
## next(obj) is same as calling obj.__next__() method
# prints 11
print(our_iter.__next__())
# prints 33
print(our_iter.__next__())
# This will raise error, no items left
# print (our_iter.__next__())
44
77
11
33
#Creating a custom iterrator
class Pow_of_Two:
'''Class to implement an iterator
of powers of two'''
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
self.constant_number = 2
return self
def __next__(self):
if self.n <= self.max:
result = self.constant_number ** self.n
self.n += 1
return result
else:
raise StopIteration
print(Pow_of_Two.__doc__)
a = Pow_of_Two(4) # create an object # 4 is the max value
i = iter(a) # create an iterable object
print(next(i)) # print the first item from the iterator
print(next(i)) # print the next item from the iterator
print(next(i)) # print the next item from the iterator
print(next(i)) # print the next item from the iterator
print(next(i)) # print the last item from the iterator
Class to implement an iterator
of powers of two
1
2
4
8
16
#Creating an infinite iterator
class InfIter:
'''Infinite iterator to return all
odd numbers'''
def __iter__(self):
self.num = 1
return self
def __next__(self):
num = self.num
self.num += 2
return num
a = iter(InfIter())
print(next(a))
print(next(a))
print(next(a))
print(next(a))
1
3
5
7
Iterations using for loop#
# Printing all the elements present in a set
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in a:
print(i, end=" ")
print("hello")
1 hello
2 hello
3 hello
4 hello
5 hello
6 hello
7 hello
8 hello
9 hello
10 hello
# Using range in for Loop
for i in range(6, 11, 2):
print(i)
6
8
10
# Using for Loop for printing the values present in the # tuple and using the else command in the for Loop
b = (11, 12, 13, 14, 15)
for i in b:
print(i)
else:
print("Printing Completed!")
11
12
13
14
15
Printing Completed!
Inheritance#
# Creating Class and Object in Python
class MyBird:
def __init__(self):
print("myBird class constructor is executing...")
def whatType(self):
print("I am a Bird...")
def canSwim(self):
print("I can Swim...")
#myPenguin class inheriting the attributes from the myBird class
class myPenguin(MyBird):
def __init__(self):
# call super() function
super().__init__()
print("myPenguin class constructor is executing...")
def whoisThis(self):
print("I am Penguin...")
def canRun(self):
print("I can run faster...")
# Accessing the child class's attributes (Inheritance)
pg1 = myPenguin()
pg1.whatType() #defined in myBird class
pg1.whoisThis() #defined in myPenguin class
pg1.canSwim() #defined in myBird class
pg1.canRun() #defined in myPenguin class
myBird class constructor is executing...
myPenguin class constructor is executing...
I am a Bird...
I am Penguin...
I can Swim...
I can run faster...
# Polymorphism
class MyParrot:
def canFly(self):
print("Parrot can fly...\n")
def canSwim(self):
print("Parrot can't swim...\n")
class MyPenguin:
def canFly(self):
print("Penguin can't fly...\n")
def canSwim(self):
print("Penguin can swim...\n")
# common interface
def flying_bird_test(bird):
bird.canFly()
bird.canSwim()
# instantiate objects
bird_parrot = MyParrot()
bird_penguin = MyPenguin()
#passing the object
flying_bird_test(bird_parrot)
flying_bird_test(bird_penguin)
Parrot can fly...
Parrot can't swim...
Penguin can't fly...
Penguin can swim...
Multiple Inheritance#
# Multiple Inheritance
class Basel:
pass
class Base2:
pass
class MultiDerived(Basel, Base2):
pass
# Multiple Inheritance
class Base1:
def funcBasel(self):
print("funcBase1() is executing...")
class Base2:
def funcBase2(self):
print("funcBase2() is executing...")
class Base3:
def funcBase3(self):
print("funcBase3() is executing...")
class MultiDerived(Base1, Base2, Base3):
def funcMultiDerived(self):
print("funcMultiDerived() is executing...")
# Creating an object of the derived class
objMD = MultiDerived()
objMD.funcBasel()
objMD.funcBase2()
objMD.funcBase3()
objMD.funcMultiDerived()
funcBase1() is executing...
funcBase2() is executing...
funcBase3() is executing...
funcMultiDerived() is executing...
#use inti and super
class Base1:
def __init__(self):
self.str1 = "Geek1"
print("Base1")
class Base2:
def __init__(self):
self.str2 = "Geek2"
print("Base2")
class Derived(Base1, Base2):
def __init__(self):
# Calling constructors of Base1
# and Base2 classes
# super().__init__() will call the __init__() method of the Base1 class only
Base1.__init__(self)
Base2.__init__(self)
print("Derived")
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()
Base1
Base2
Derived
Geek1 Geek2
Function Arguments#
def findMax(a, b):
"""Function taking arguments and returning a value."""
if a>b:
return a
else:
return b
print("Max number between 10 and 20 is ",findMax(10,20))
Max number between 10 and 20 is 20
def hello(name, msg="how are you?"):
"""Function with default parameter."""
print("Hello",name, msg)
hello("Agnibha",", have a nice day.")
hello("Agnibha")
Hello Agnibha , have a nice day.
Hello Agnibha how are you?
def sumArg(*args):
"""Function with arbitrary arguments."""
sum=0
for i in args:
sum += i
return sum
print("Sum of all the integers between 1-5 is ", sumArg(1,2,3,4,5))
Sum of all the integers between 1-5 is 15
def defaultArg(a, b, c=200):
"""Function with default argument."""
print("a = {} b = {} c = {}".format(a,b,c))
defaultArg(1,2,3)
defaultArg(1,2)
# defaultArg(1) # error as a and b are mandatory
defaultArg(b=2, a=1) # order of arguments can be changed
a = 1 b = 2 c = 3
a = 1 b = 2 c = 200
a = 1 b = 2 c = 200
python function#
# function without return statement
def func1():
"""This function does not return anything."""
print("Hello, I am function 1")
print("I am from Egypt")
func1()
# function with return statement
def func2():
'''This function returns a string.'''
return "I am from Egypt"
print(func2())
print(func2.__doc__)
Hello, I am function 1
I am from Egypt
I am from Egypt
This function returns a string.
def myAddition(x,y):
print("Performing the addition operation...")
return(x+y)
def mySubtraction(x,y):
print("Performing the subtraction operation...")
return(x-y)
def myMultiplication(x,y):
print("Performing the multiplication operation...")
return(x*y)
def myDivision(x,y):
print("Performing the division operation...")
return(x/y)
def myMenu():
print("Main Menu...")
print("1 > Addition operation...")
print("2 > Subtraction operation...")
print("3 > Multiplication operation...")
print("4 > Division operation...")
# make a validation for the input with isdigit() function
while True:
ch = input("Please enter your choice...")
if ch.isdigit():
ch = int(ch)
if ch>=1 and ch<=4:
return ch
else:
print("Invalid choice, please enter a valid choice...")
else:
print("Invalid choice, please enter a valid choice...")
def calculation():
ch = myMenu()
while True:
try:
num1 = int(input("Please enter the first number..."))
num2 = int(input("Please enter the second number..."))
break
except ValueError:
print("Invalid input, please enter a valid number...")
if ch == 1:
print("The result of the addition operation is ", myAddition(num1,num2))
elif ch == 2:
print("The result of the subtraction operation is ", mySubtraction(num1,num2))
elif ch == 3:
print("The result of the multiplication operation is ", myMultiplication(num1,num2))
elif ch == 4:
print("The result of the division operation is ", myDivision(num1,num2))
else:
print("Invalid choice, please enter a valid choice...")
calculation()
Main Menu...
1 > Addition operation...
2 > Subtraction operation...
3 > Multiplication operation...
4 > Division operation...
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[135], line 52
49 else:
50 print("Invalid choice, please enter a valid choice...")
---> 52 calculation()
Cell In[135], line 33, in calculation()
32 def calculation():
---> 33 ch = myMenu()
34 while True:
35 try:
Cell In[135], line 21, in myMenu()
19 # make a validation for the input with isdigit() function
20 while True:
---> 21 ch = input("Please enter your choice...")
22 if ch.isdigit():
23 ch = int(ch)
File ~/work/python-revision/python-revision/.venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1274, in Kernel.raw_input(self, prompt)
1272 if not self._allow_stdin:
1273 msg = "raw_input was called, but this frontend does not support input requests."
-> 1274 raise StdinNotImplementedError(msg)
1275 return self._input_request(
1276 str(prompt),
1277 self._parent_ident["shell"],
1278 self.get_parent("shell"),
1279 password=False,
1280 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
Break statement#
import random as r
rand_num = r.randrange(1,20) # Generating a random number between 1 and 19
print("Number to be guessed: ", rand_num)
i = 1
while True:
print("Number Guessed: ",i)
if(i == rand_num): # If the number guessed is correct the this block will be executed
print("Random Number has been guessed successfully!")
break # Break statements stops and exits from the Loop
i += 1
print("End of the program")
Number to be guessed: 16
Number Guessed: 1
Number Guessed: 2
Number Guessed: 3
Number Guessed: 4
Number Guessed: 5
Number Guessed: 6
Number Guessed: 7
Number Guessed: 8
Number Guessed: 9
Number Guessed: 10
Number Guessed: 11
Number Guessed: 12
Number Guessed: 13
Number Guessed: 14
Number Guessed: 15
Number Guessed: 16
Random Number has been guessed successfully!
End of the program
Continue statement#
for i in range(1,11):
if(i == 5):
continue # Continue statement skips the current iteration and continues with the next iteration
print(i)
1
2
3
4
6
7
8
9
10
# Program to print the odd numbers between 1 and 10
for i in range(1,11):
if(i%2 == 0):
continue
print(i)
1
3
5
7
9
# Program to print the even numbers between 1 and 10
for i in range(1,11):
if(i%2 != 0):
continue
print(i)
2
4
6
8
10
Error Handling#
try:
"""The code which can give rise to an exception is written here."""
a = "hi"
b = int(a)
except:
print("Exception caught!")
Exception caught!
# Catching specific exception
try:
a = 5
b = 0
c = a/b
except ZeroDivisionError:
print("Division by zero is not possible")
Division by zero is not possible
# Exceptions can be raised also
try:
raise TypeError
except TypeError:
print("TypeError Exception caught!")
TypeError Exception caught!
# try except finally else
try:
a = 10
b = 0
c = a/b
except ZeroDivisionError:
print("Division by zero is not possible")
else:
print("Division successful") # This will be executed if no exception is raised
finally:
print("This will be executed no matter what")
Division by zero is not possible
This will be executed no matter what
# Catching specific exception try:
try:
a = int(input("Please enter the first number..."))
b = int(input("Please enter the second number..."))
if (a < 0):
raise TypeError
c = a/b
print("{} / {} = {}".format(a,b,c))
except ZeroDivisionError:
print("Division by zero is not possible")
except ValueError:
print("The data types are not proper")
except TypeError:
print("The data is not in range")
except NameError:
print("The variable is not defined")
except:
print("Some other exception")
else:
print("Division successful") # This will be executed if no exception is raised
finally:
print("This will be executed no matter what")
Some other exception
This will be executed no matter what
class MyException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
try:
raise MyException(2*2)
except MyException as error:
print('A New Exception occured: ',error.value)
A New Exception occured: 4
# another custom exception
class VoterEligibilityException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
try:
age = int(input("Please enter your age..."))
if(age < 18):
raise VoterEligibilityException("You are not eligible to vote")
except VoterEligibilityException as error:
print(error.value)
except TypeError:
print("The data types are not proper")
except ValueError:
print("The data types are not proper")
else:
print("You are eligible to vote")
finally:
print("Thank you for using our application")
Thank you for using our application
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[146], line 10
7 return str(self.value)
9 try:
---> 10 age = int(input("Please enter your age..."))
11 if(age < 18):
12 raise VoterEligibilityException("You are not eligible to vote")
File ~/work/python-revision/python-revision/.venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1274, in Kernel.raw_input(self, prompt)
1272 if not self._allow_stdin:
1273 msg = "raw_input was called, but this frontend does not support input requests."
-> 1274 raise StdinNotImplementedError(msg)
1275 return self._input_request(
1276 str(prompt),
1277 self._parent_ident["shell"],
1278 self.get_parent("shell"),
1279 password=False,
1280 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
OOP in Python#
class myBird:
def __init__(self):
print("Bird is ready")
def whatType(self):
print("I am a bird")
def can_fly(self):
print("I can fly")
class MyParrot(myBird):
# class attribute
species = "bird"
def __init__(self, name, age):
print("Parrot is ready")
self.name = name
self.age = age
def can_sing(self, sound):
return "{} can sing {}".format(self.name, sound)
# myPenguin class inherits the properties of myBird class
class MyPenguin(myBird):
def __init__(self):
super().__init__()
print("Penguin is ready")
def whatType(self):
print("I am a Penguin")
def can_run(self):
print("Penguin can run")
# instantiate the Parrot class
mp1 = MyParrot("MyParrot1", 10)
mp2 = MyParrot("MyParrot2", 15)
# access the class attributes
print("MP1 is a {}".format(mp1.__class__.species))
print("MP2 is also a {}".format(mp2.__class__.species))
# access the instance attributes
print("{} is {} years of age".format(mp1.name, mp1.age))
print("{} is {} years of age".format(mp2.name, mp2.age))
print(mp1.can_sing("Chirp"))
# Accessing the child class's attributes (Inheritance)
pg1 = MyPenguin()
pg1.whatType()
pg1.can_fly()
pg1.can_run()
Parrot is ready
Parrot is ready
MP1 is a bird
MP2 is also a bird
MyParrot1 is 10 years of age
MyParrot2 is 15 years of age
MyParrot1 can sing Chirp
Bird is ready
Penguin is ready
I am a Penguin
I can fly
Penguin can run
# Data encapsulation
class PersonalComputer:
# class attribute
brand = "MacBook Pro"
def __init__(self):
self.__maxprice = 90000 # Private attribute
self.minprice = 17000 # Public attribute
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
print("Selling Price: {}\n".format(self.minprice))
def setMaxPrice(self, price):
self.__maxprice = price
pc1 = PersonalComputer()
pc1.sell()
# change the price
pc1.__maxprice = 100000 # This will not change the price as it is a private attribute
pc1.sell() # Still prints the old price
pc1.minprice = 15000 # This will change the price as it is a public attribute
pc1.sell() # Prints the new price
# using setter function
pc1.setMaxPrice(100001)
pc1.sell()
# print(pc1.__maxprice) # This will not print the price as it is a private attribute
print(pc1._PersonalComputer__maxprice) # This will print the price as it is a private attribute
print(pc1.__class__.brand) # This will print the price as it is a public attribute
# print(PersonalComputer.__maxprice) # This will not print the price as it is a private attribute
print()
print(pc1.minprice) # This will print the price as it is a public attribute
# print(PersonalComputer.minprice) # This will not print the minprice because it's not a class attribute
# print(pc1.__class__.minprice) # This will not print the minprice because it's not a class attribute
print()
print(pc1.brand) # This will print the price as it is a public attribute
print(PersonalComputer.brand) # This will print the price as it is a public attribute
print(pc1.__class__.brand) # This will print the price as it is a public attribute
Selling Price: 90000
Selling Price: 17000
Selling Price: 90000
Selling Price: 17000
Selling Price: 90000
Selling Price: 15000
Selling Price: 100001
Selling Price: 15000
100001
MacBook Pro
15000
MacBook Pro
MacBook Pro
MacBook Pro
Nested Dictionary#
# Declaring and defining a nested dictionary
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people)
# Accessing elements of the dictionary
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
John
27
Male
# Adding elements to a nested dictionary
people[3] = {} # Adding an empty dictionary to the 3rd key
people[3]['name'] = 'Luna' # Adding name to the 3rd key
people[3]['age'] = '24' # Adding age to the 3rd key
people[3]['sex'] = 'Female' # Adding gender to the 3rd key
people[3]['married'] = 'No' # Adding married status to the 3rd key
print(people)
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}, 3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}}
people[4] = {'name':'Mohammed','age':'26','sex':'Male','married':'Yes'}
print(people[4],'\n')
print(people)
{'name': 'Mohammed', 'age': '26', 'sex': 'Male', 'married': 'Yes'}
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}, 3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}, 4: {'name': 'Mohammed', 'age': '26', 'sex': 'Male', 'married': 'Yes'}}
print(people[3])
print(people[4])
del people[3]['married']
del people[4]['married']
print(people[3],'\n')
print(people[4])
{'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}
{'name': 'Mohammed', 'age': '26', 'sex': 'Male', 'married': 'Yes'}
{'name': 'Luna', 'age': '24', 'sex': 'Female'}
{'name': 'Mohammed', 'age': '26', 'sex': 'Male'}
del people[3], people[4]
print(people)
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people.items())
for p_id, p_info in people.items():
print("\nPerson ID:", p_id)
for key in p_info:
print(key + ':', p_info[key])
dict_items([(1, {'name': 'John', 'age': '27', 'sex': 'Male'}), (2, {'name': 'Marie', 'age': '22', 'sex': 'Female'})])
Person ID: 1
name: John
age: 27
sex: Male
Person ID: 2
name: Marie
age: 22
sex: Female
Python Operators#
# Operator OverLoading
class MyPoint:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
# Overloading + operator
def __add__(self, other):
y = self.y + other.y
x = self.x + other.x
return MyPoint(x, y)
# OverLoading < Operator
def __lt__(self, other):
self_mag = (self.x ** 2) + (self.y ** 2)
other_mag = (other.x ** 2) + (other.y ** 2)
return self_mag< other_mag
p1 = MyPoint(1,2)
p2 = MyPoint(4,5)
print(p1)
print(p2)
print()
print(p1<p2)
print(p1+p2)
print()
print(p1.__lt__(p2))
print(p1.__add__(p2))
(1,2)
(4,5)
True
(5,7)
True
(5,7)
Python comments and statements#
# This is a comment
# This is a Long comment
# and multi-line comments
# can be written like this
'''Multi-line comments can also be written like this.'''
'Multi-line comments can also be written like this.'
# statment - assign a value to a variable
a = 1
# Multiline statement
# Explicit the line continuation character (\)
b = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
print(b)
# Explicit the line continuation within brackets
c = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
print(c)
45
45
# Multiple statements in one line using
d = 1; e = 3; f = 0
print(d,e,f)
1 3 0
# Code block (body of a function, Loop etc.) starts with indentation
# and ends with the first unindented Line.
for i in range(1,10):
print(i)
if i == 5:
break
print("End of the program...")
1
2
3
4
5
End of the program...
Pass statment#
# pass is just a placeholder for #functionality to be added Later.
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
print("End of the program...")
End of the program...
Python generators#
# a simple generator function
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 2
print('This is printed at last')
yield n
a = my_gen()
next(a)
next(a)
next(a)
print("Using for loop")
for i in my_gen():
print(i)
This is printed first
This is printed second
This is printed at last
Using for loop
This is printed first
1
This is printed second
2
This is printed at last
4
# Generator function with for loop
# reverse string
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
for char in rev_str("hello"):
print(char, end="")
print()
print("hello"[::-1])
olleh
olleh
Python Decorators#
# Demonstrating without @
def decor(func):
def inner():
print("Decorated function")
func()
return inner
def ordinary():
print("Ordinary function")
print("without Using @")
ordinary()
print()
decorated = decor(ordinary)
print(decorated) # <function decor.<locals>.inner at 0x0000020F4F6F2D08>
decorated()
without Using @
Ordinary function
<function decor.<locals>.inner at 0x7f3a20ef5c60>
Decorated function
Ordinary function
# Demonstrating with @
def decor(func):
def inner():
print("Decorated function")
func()
return inner
@decor
def ordinary():
print("Ordinary function")
print("Using @")
ordinary()
print(ordinary) #<function decor.<locals>.inner at 0x10f406e80>
print(decor(ordinary)) # <function decor.<locals>.inner at 0x10f406b60>
print(decor) # <function decor at 0x10f406840>
print("\nwithout Using @")
def ordinary():
print("Ordinary function")
ordinary()
print(ordinary) # <function ordinary at 0x10f406b60>
print(decor(ordinary)) # <function decor.<locals>.inner at 0x10f406e80>
print(decor) # <function decor at 0x10f406840>
Using @
Decorated function
Ordinary function
<function decor.<locals>.inner at 0x7f3a20ef59e0>
<function decor.<locals>.inner at 0x7f3a20ef5ee0>
<function decor at 0x7f3a20ef5bc0>
without Using @
Ordinary function
<function ordinary at 0x7f3a20ef5ee0>
<function decor.<locals>.inner at 0x7f3a20ef59e0>
<function decor at 0x7f3a20ef5bc0>
# Python Decorator to print function name before and after execution
def decorator_func(func):
def wrapper_func():
print("Before calling the function")
func()
print("After calling the function")
return wrapper_func
@decorator_func
def func_to_be_used():
print("Inside the function")
func_to_be_used()
Before calling the function
Inside the function
After calling the function
# Python Decorator to perform the same task as above
def my_smart_div(func):
def inner_func(x,y):
print("I am dividing ",x," and ",y)
if y == 0:
print("Oops! Division by ZERO is illegal...!!!")
return # None
return func(x,y) # go_divide(x,y)
return inner_func
@my_smart_div
def go_divide(a,b):
return a/b
# Generally, we decorate a function and reassign it as, # go_divide = my_smart_div(go_divide)
# But this is similar to the above statement
print(go_divide (20,2))
print(go_divide (20,0))
I am dividing 20 and 2
10.0
I am dividing 20 and 0
Oops! Division by ZERO is illegal...!!!
None
# Demonstrating the order of execution of decorators
def decor1(func):
def inner():
x = func()
return x * x
return inner
def decor2(func):
def inner():
x = func()
return 2 * x
return inner
@decor2
@decor1
def num():
return 10
print(num())
200
While loop#
# Using while Loop
i = 3
while i > 0:
print(i)
i -= 1
3
2
1
while i < 10:
print(i)
i += 1
else:
print("i is no longer less than 10")
0
1
2
3
4
5
6
7
8
9
i is no longer less than 10
“”” n = 6 i . * ___________________
1 5 1 . = -> n - i
2 4 3
3 3 5 * = -> 2*i - 1
4 2 7
5 1 9
6 0 11
___________________
…..* ….*** …***** ..******* .*********
“””
n = int(input("Please enter the number of layers..."))
i = 1
while i <= n:
# print spaces
j = 1
while j <= n - i:
print(".", end="")
j = j + 1
# print stars
j = 1
while j <= 2*i - 1:
print("*", end="")
j = j + 1
# print spaces
print()
i = i + 1
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[175], line 1
----> 1 n = int(input("Please enter the number of layers..."))
2 i = 1
3 while i <= n:
4 # print spaces
File ~/work/python-revision/python-revision/.venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1274, in Kernel.raw_input(self, prompt)
1272 if not self._allow_stdin:
1273 msg = "raw_input was called, but this frontend does not support input requests."
-> 1274 raise StdinNotImplementedError(msg)
1275 return self._input_request(
1276 str(prompt),
1277 self._parent_ident["shell"],
1278 self.get_parent("shell"),
1279 password=False,
1280 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
“”” n = 11(odd) m = (n+1)/2 = 6
i . *
___________________
1 0 11 . = -> i - 1
2 1 9
3 2 7
4 3 5
5 4 3 * = -> 2*(m-i) + 1
6 5 1
_______
7 4 3 . = -> n - i
8 3 5
9 2 7
10 1 9 * = -> 2*(i-m) + 1
11 0 11
___________________
.********* ..******* …***** ….*** …..* ….*** …***** ..******* .*********
“””
n = int(input("Please enter the odd number of layers..."))
m = (n+1)/2
i = 1
while i <= n:
if (i > m):
b = n-i
s= 2*(i-m)+1
else:
b=i-1
s = 2*(m-i)+1
j = 1
while j <= b:
print(".", end="")
j = j+1
j = 1
while j <= s:
print("*", end="")
j = j + 1
print()
i = i + 1
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[176], line 1
----> 1 n = int(input("Please enter the odd number of layers..."))
2 m = (n+1)/2
3 i = 1
File ~/work/python-revision/python-revision/.venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1274, in Kernel.raw_input(self, prompt)
1272 if not self._allow_stdin:
1273 msg = "raw_input was called, but this frontend does not support input requests."
-> 1274 raise StdinNotImplementedError(msg)
1275 return self._input_request(
1276 str(prompt),
1277 self._parent_ident["shell"],
1278 self.get_parent("shell"),
1279 password=False,
1280 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
“”” n = 11(odd) m = (n+1)/2 = 6
i . *
___________________
1 5 1
2 4 3 . = -> m - i
3 3 5
4 2 7 * = -> 2*i - 1
5 1 9
6 0 11
_____
7 1 9
8 2 7 . = -> i - m
9 3 5
10 4 3 * = -> 2*(m-i) + n
11 5 1
___________________
…..* ….*** …***** ..******* .*********
.********* ..******* …***** ….*** …..*
“””
n = 11
m = (n+1)/2 # 6
i = 1
while i <= n:
if (i < m):
b = m-i
s= 2*i - 1
else:
b= i-m
s = 2*(m-i) + n
j = 1
while j <= b:
print(".", end="")
j = j + 1
j = 1
while j <= s:
print("*", end="")
j = j + 1
print()
i = i + 1
.....*
....***
...*****
..*******
.*********
***********
.*********
..*******
...*****
....***
.....*
if…elif..else#
# if...elif..else
age = int(input("Please enter the age of the person..."))
if age < 5:
print("Too young")
elif age == 5:
print("Kindergarten")
elif ((age >5) and (age <= 17)):
grade = age - 5
print("Go to {} grade".format(grade))
else:
print("Go to college")
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[178], line 2
1 # if...elif..else
----> 2 age = int(input("Please enter the age of the person..."))
3 if age < 5:
4 print("Too young")
File ~/work/python-revision/python-revision/.venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1274, in Kernel.raw_input(self, prompt)
1272 if not self._allow_stdin:
1273 msg = "raw_input was called, but this frontend does not support input requests."
-> 1274 raise StdinNotImplementedError(msg)
1275 return self._input_request(
1276 str(prompt),
1277 self._parent_ident["shell"],
1278 self.get_parent("shell"),
1279 password=False,
1280 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
num = float(input("Please enter a number..."))
if num >= 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[179], line 1
----> 1 num = float(input("Please enter a number..."))
2 if num >= 0:
3 print("Positive number")
File ~/work/python-revision/python-revision/.venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1274, in Kernel.raw_input(self, prompt)
1272 if not self._allow_stdin:
1273 msg = "raw_input was called, but this frontend does not support input requests."
-> 1274 raise StdinNotImplementedError(msg)
1275 return self._input_request(
1276 str(prompt),
1277 self._parent_ident["shell"],
1278 self.get_parent("shell"),
1279 password=False,
1280 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
# a is 2-D matrix with integers
a = [
['Roy',80,75,85,90,95],
['John',75,80,75,85,100],
['Dave', 80, 80, 80, 90, 95]
]
# b is a nested list but not a matrix
b= [
['Roy',80,75,85,90,95],
['John',75,80,75],
['Dave', 80, 80, 80, 90,95]
]
print(a)
print()
print(b)
[['Roy', 80, 75, 85, 90, 95], ['John', 75, 80, 75, 85, 100], ['Dave', 80, 80, 80, 90, 95]]
[['Roy', 80, 75, 85, 90, 95], ['John', 75, 80, 75], ['Dave', 80, 80, 80, 90, 95]]
n = 3
m = 4
a = [0] * n
print(a)
for i in range(n):
a[i] = [0]* m
print(a)
[0, 0, 0]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# Accessing elements in a matrix
print(a)
print(a[0])
print(a[0][1])
print(a[1][2])
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[0, 0, 0, 0]
0
0
# Negative indexing
print(a)
print(a[-1])
print(a[-1][-1])
print(a[-2][-3])
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[0, 0, 0, 0]
0
0
print(a)
b = a[0]
print(b)
b[1] = 5
print(b)
print(a)
a[2] = ['Samy', 80, 75, 85, 90, 95]
print(a)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[0, 0, 0, 0]
[0, 5, 0, 0]
[[0, 5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 5, 0, 0], [0, 0, 0, 0], ['Samy', 80, 75, 85, 90, 95]]
# create a dynamic matrix using nested list comprehension
rows = int(input("Enter the number of rows..."))
cols = int(input("Enter the number of columns..."))
a = [[int(input("Enter the element...")) for i in range(cols)] for j in range(rows)]
print(a)
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[185], line 2
1 # create a dynamic matrix using nested list comprehension
----> 2 rows = int(input("Enter the number of rows..."))
3 cols = int(input("Enter the number of columns..."))
4 a = [[int(input("Enter the element...")) for i in range(cols)] for j in range(rows)]
File ~/work/python-revision/python-revision/.venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1274, in Kernel.raw_input(self, prompt)
1272 if not self._allow_stdin:
1273 msg = "raw_input was called, but this frontend does not support input requests."
-> 1274 raise StdinNotImplementedError(msg)
1275 return self._input_request(
1276 str(prompt),
1277 self._parent_ident["shell"],
1278 self.get_parent("shell"),
1279 password=False,
1280 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
Regular Expressions#
# Regular expressions allow you to locate and change # strings in very powerful ways.
# They work in almost exactly the same way in every # programming Language as well.
# Regular Expressions (Regex) are used to
# 1. Search for a specific string in a large amount of data # 2. Verify that a string has the proper format (Email, Phone #)
# 3. Find a string and replace it with another string
# 4. Format data into the proper form for importing for example
#import the Regex module
import re
#
# ......... Was a Match Found ......
# Search for ape in the string
if re.search("ape", "The ape was at the apex"):
print("There is an ape")
There is an ape
import re
# Get ALL Matches
#findall () returns a list of matches # . is used to match any 1 character or spake
allApes = re.findall("ape.", "The ape was at the apex")
for i in allApes:
print(i)
ape
apex
#finditer returns an iterator of matching objects # You can use span to get the location
theStr = "The ape was at the apex"
for i in re.finditer ("ape.", theStr):
# Span returns a tuple
locTuple = i.span()
print(locTuple)
# Slice the match out using the tuple values
print(theStr[locTuple[0]:locTuple[1]])
(4, 8)
ape
(19, 23)
apex
import re
# Match 1 of Several Letters
# Square brackets will match any one of the characters between # the brackets not including upper and Lowercase varieties # unless they are listed
animalStr = "Cat rat mat fat pat Tat"
allAnimals = re.findall("[crmfptT]at", animalStr)
for i in allAnimals:
print(i)
print()
rat
mat
fat
pat
Tat
# We can also allow for characters in a range
# Remember to include upper and Lowercase Letters
animalStr = "Cat rat mat fat pat"
someAnimals = re.findall("[c-mC-M]at", animalStr) # [a-zA-Z]at would match any animal
for i in someAnimals:
print(i)
print()
Cat
mat
fat
# Use to denote any character but whatever characters are # between the brackets
animalStr = "Cat rat mat fat pat"
someAnimals = re.findall("[^Cr]at", animalStr) # [^Cr]at would match any animal except Cat and rat
for i in someAnimals:
print(i)
print()
mat
fat
pat
import re
# _______ Replace ALL Matches _______
# Replace matching items in a string
owlFood = "rat cat mat pat"
# You can compile a regex into pattern objects which # provide additional methods
regex = re.compile("[cr]at")
# sub() replaces items that match the regex in the string
# with the 1st attribute string passed to sub owl Food
owlFood = regex.sub("owl", owlFood)
print(owlFood)
owl owl mat pat
import re
# -------- Solving Backslash Problems ---------
# Regex use the backslash to designate special characters
# and Python does the same inside strings which causes issues.
# Let's try to get "\\stuff" out of a string
randStr = "Here is \\stuff"
# This won't find it
print("Find \\stuff: ", re.search("\\stuff", randStr))
# This does, but we have to put in 4 slashes which is messy
print("Find \\stuff: ", re.search("\\\\stuff", randStr))
# You can get around this by using raw strings which # don't treat backslashes as special
print("Find \\stuff: ", re.search(r"\\stuff", randStr))
Find \stuff: None
Find \stuff: <re.Match object; span=(8, 14), match='\\stuff'>
Find \stuff: <re.Match object; span=(8, 14), match='\\stuff'>
import re
# Matching Any Character
# We saw that matches any character, but what if we #want to match a period. Backslash the period # You do the same with [, ] and others
randStr = "F.B.I. I.R.S. CIA"
print("Matches ", len(re.findall(".\..\..", randStr))) # . is any character while \. is actually a period '.'
print("Matches :", re.findall(".\..\..", randStr))
Matches 2
Matches : ['F.B.I', 'I.R.S']
<>:5: SyntaxWarning: invalid escape sequence '\.'
<>:6: SyntaxWarning: invalid escape sequence '\.'
<>:5: SyntaxWarning: invalid escape sequence '\.'
<>:6: SyntaxWarning: invalid escape sequence '\.'
/tmp/ipykernel_2356/1147912209.py:5: SyntaxWarning: invalid escape sequence '\.'
print("Matches ", len(re.findall(".\..\..", randStr))) # . is any character while \. is actually a period '.'
/tmp/ipykernel_2356/1147912209.py:6: SyntaxWarning: invalid escape sequence '\.'
print("Matches :", re.findall(".\..\..", randStr))
import re
# Matching Whitespace
# We can match many whitespace characters
randStr = """This is a long
string that goes
on for many lines"""
print (randStr)
# Remove newlines
regex = re.compile("\n")
randStr = regex.sub(" ", randStr)
print (randStr)
# You can also match
# \b: Backspace
# \f Form Feed
# \r : Carriage Return
# \t : Tab
# \v : Vertical Tab
# You may need to remove \r\n on Windows
This is a long
string that goes
on for many lines
This is a long string that goes on for many lines
import re
# Matching Any Single Number
# \d can be used instead of [0-9]
# \D is the same as [^0-9]
randStr = "12345"
print("Matches :", len(re.findall("\d", randStr)))
print("Matches :", re.findall("\d", randStr))
Matches : 5
Matches : ['1', '2', '3', '4', '5']
<>:6: SyntaxWarning: invalid escape sequence '\d'
<>:7: SyntaxWarning: invalid escape sequence '\d'
<>:6: SyntaxWarning: invalid escape sequence '\d'
<>:7: SyntaxWarning: invalid escape sequence '\d'
/tmp/ipykernel_2356/4134592694.py:6: SyntaxWarning: invalid escape sequence '\d'
print("Matches :", len(re.findall("\d", randStr)))
/tmp/ipykernel_2356/4134592694.py:7: SyntaxWarning: invalid escape sequence '\d'
print("Matches :", re.findall("\d", randStr))
import re
# Matching Multiple Numbers
# You can match multiple digits by following the \d with {numOfValues}
# Match 5 numbers] only
if re.search("\d{5}", "12345"): # Match 5 numbers
print("It is a zip code")
# You can also match within a range # Match values that are between 5 and 7 digits
numStr = "123 12345 123456 1234567"
print("Matches :", len(re.findall("\d{5,7}", numStr))) # Match 5 to 7 numbers
print("Matches :", re.findall("\d{5,7}", numStr))
It is a zip code
Matches : 3
Matches : ['12345', '123456', '1234567']
<>:5: SyntaxWarning: invalid escape sequence '\d'
<>:9: SyntaxWarning: invalid escape sequence '\d'
<>:10: SyntaxWarning: invalid escape sequence '\d'
<>:5: SyntaxWarning: invalid escape sequence '\d'
<>:9: SyntaxWarning: invalid escape sequence '\d'
<>:10: SyntaxWarning: invalid escape sequence '\d'
/tmp/ipykernel_2356/2058430638.py:5: SyntaxWarning: invalid escape sequence '\d'
if re.search("\d{5}", "12345"): # Match 5 numbers
/tmp/ipykernel_2356/2058430638.py:9: SyntaxWarning: invalid escape sequence '\d'
print("Matches :", len(re.findall("\d{5,7}", numStr))) # Match 5 to 7 numbers
/tmp/ipykernel_2356/2058430638.py:10: SyntaxWarning: invalid escape sequence '\d'
print("Matches :", re.findall("\d{5,7}", numStr))
import re
# Matching Any Single Letter or Number
# \w is the same as [a-zA-Z0-9_]
# \W is the same as [^a-zA-Z0-9_]
phNum = "412-555-1212"
# Check if it is a phone number
if re.search("\w{3}-\w{3}-\w{4}", phNum):
print("It is a phone number")
# Check for valid first name between 2 and 20 characters
if re.search("\w{2,20}", "Ultraman"):
print("It is a valid name")
It is a phone number
It is a valid name
<>:7: SyntaxWarning: invalid escape sequence '\w'
<>:10: SyntaxWarning: invalid escape sequence '\w'
<>:7: SyntaxWarning: invalid escape sequence '\w'
<>:10: SyntaxWarning: invalid escape sequence '\w'
/tmp/ipykernel_2356/2600091984.py:7: SyntaxWarning: invalid escape sequence '\w'
if re.search("\w{3}-\w{3}-\w{4}", phNum):
/tmp/ipykernel_2356/2600091984.py:10: SyntaxWarning: invalid escape sequence '\w'
if re.search("\w{2,20}", "Ultraman"):
import re
# Matching WhiteSpace
# \s is the same as [\f\n\r\t\v]
# \S is the same as [^\f\n\r\t\v]
# Check for valid first and last name with a space
if re.search("\w{2,20}\s\w{2,20}", "Toshio Muramatsu"):
print("It is a valid full name")
It is a valid full name
<>:6: SyntaxWarning: invalid escape sequence '\w'
<>:6: SyntaxWarning: invalid escape sequence '\w'
/tmp/ipykernel_2356/1408926825.py:6: SyntaxWarning: invalid escape sequence '\w'
if re.search("\w{2,20}\s\w{2,20}", "Toshio Muramatsu"):
import re
# Matching One or More
# + matches 1 or more characters
# Match a followed by 1 or more characters
print("Matches", len (re.findall("a+", "a as ape bug")))
print("Matches :", re.findall("a+", "a as ape bug"))
Matches 3
Matches : ['a', 'a', 'a']
import re
# Problem
# Create a Regex that matches email addresses from a list # 1. 1 to 20 Lowercase and uppercase letters, numbers, plus _%+-
# 2. An@ symbol
# 3. 2 to 20 Lowercase and uppercase letters, numbers, plus .- I
# 4. A period
# 5. 2 to 3 Lowercase and uppercase letters
emailList = "db@aol.com m@.com @apple.com db@.com"
print("Email Matches :", len(re.findall("[\w._%+-]{1,20}@[\w.-]{2,20}.[A-Za-z]{2,3}",emailList)))
print("Email Matches :", re.findall("[\w._%+-]{1,20}@[\w.-]{2,20}.[A-Za-z]{2,3}",emailList))
Email Matches : 1
Email Matches : ['db@aol.com']
<>:9: SyntaxWarning: invalid escape sequence '\w'
<>:10: SyntaxWarning: invalid escape sequence '\w'
<>:9: SyntaxWarning: invalid escape sequence '\w'
<>:10: SyntaxWarning: invalid escape sequence '\w'
/tmp/ipykernel_2356/2030932851.py:9: SyntaxWarning: invalid escape sequence '\w'
print("Email Matches :", len(re.findall("[\w._%+-]{1,20}@[\w.-]{2,20}.[A-Za-z]{2,3}",emailList)))
/tmp/ipykernel_2356/2030932851.py:10: SyntaxWarning: invalid escape sequence '\w'
print("Email Matches :", re.findall("[\w._%+-]{1,20}@[\w.-]{2,20}.[A-Za-z]{2,3}",emailList))
List Comprehensions#
# Iterating a string through a for Loop and adding the Letters to a list
h_letters = []
for letter in 'human':
h_letters.append(letter)
print (h_letters)
['h', 'u', 'm', 'a', 'n']
# Using comprehension
h_letters = [letter for letter in 'human']
print(h_letters)
['h', 'u', 'm', 'a', 'n']
# List Comprehensions vs Lambda Function
h_letters = list(map(lambda x: x, 'human'))
print(h_letters)
['h', 'u', 'm', 'a', 'n']
# If with List comprehension
number_list = [x for x in range(20) if x%2==0]
print(number_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested If with list comprehension
num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(num_list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(obj)
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
# Transpose of Matrix using Nested Loops
matrix = [[1, 2], [3,4], [5,6], [7,8]]
transpose = [[row[i] for row in matrix] for i in range(2)] # i == 0, 1
# 2 is the number of columns in matrix
# row[i] for row in matrix] is the number of rows in matrix
#row[i] == 0 in each row in the first column # 1, 3, 5, 7
# row[i] == 1 in each row in the second column # 2, 4, 6, 8
print(transpose)
[[1, 3, 5, 7], [2, 4, 6, 8]]
Python Recursion#
# Factorial of a number
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1)) # 4 * 3 * 2 * 1
num = 4
print("The factorial of", num, "is", calc_factorial(num))
The factorial of 4 is 24
Python Input, Output#
#print function and it's usage
print('This sentence is output to the screen') # Output: This sentence is output to the screen
a = 5
print('The value of a is', a) # Output: The value of a is 5
print (1,2,3,4) # Output: 1 2 3 4
This sentence is output to the screen
The value of a is 5
1 2 3 4
print(1,2,3,4,sep='*') # Output: 1*2*3*4
print(1,2,3,4, sep='#', end='&') # Output: 1#2#3#4&
print('I love {0} and {1}'.format('bread', 'butter')) # Output: I Love bread and butter
print('I love {1} and {0}'.format('bread', 'butter')) # Output: I Love butter and bread
1*2*3*4
1#2#3#4&I love bread and butter
I love butter and bread
# Python Input
num = int(input('Enter a number: '))
print(num)
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[212], line 2
1 # Python Input
----> 2 num = int(input('Enter a number: '))
3 print(num)
File ~/work/python-revision/python-revision/.venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1274, in Kernel.raw_input(self, prompt)
1272 if not self._allow_stdin:
1273 msg = "raw_input was called, but this frontend does not support input requests."
-> 1274 raise StdinNotImplementedError(msg)
1275 return self._input_request(
1276 str(prompt),
1277 self._parent_ident["shell"],
1278 self.get_parent("shell"),
1279 password=False,
1280 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
# Importing module
import math
print("The value of pi is", math.pi)
The value of pi is 3.141592653589793
x = 10
print(math.pow(x,3))
1000.0
Reading and Writing Files#
# # Open a file
#
# # Open a file for reading
#
# f = open('workfile.txt', 'r')
# f.close()
#
# # Open a file for writing
#
# f = open('workfile.txt', 'w')
# f.close()
#
# # Open a file for appending
#
# f = open('workfile.txt', 'a')
# f.close()
# # open a file in safe mode
#
# with open('workfile.txt') as f:
# read_data = f.read()
# # We can check that the file has been automatically closed.
# f.closed()
# Writing to a file
# f = open('workfile.txt', 'w')
#
# with open('workfile.txt', 'w') as f:
# f.write('This is a test\n')
# Reading from a file
# f = open('workfile.txt', 'r')
# with open('workfile.txt', 'r') as f:
# read_data = f.read()
# print(read_data)
Different looping techniques#
Python Shallowness vs Deep Copying#
# Shallow Copying
# Shallow copying means constructing a new collection object and then populating it with references to the child objects found in the original.
# The copying process does not recurse and therefore won’t create copies of the child objects themselves.
# In case of shallow copy, a reference of object is copied in other object.
# It means that any changes made to a copy of object do reflect in the original object.
# In python, this is implemented using “copy()” function.
# importing "copy" for copy operations
import copy
# initializing list 1
li1 = [1, 2, [3,5], 4]
# using copy to shallow copy
li2 = copy.copy(li1)
# original elements of list
print ("The original elements before shallow copying")
for i in range(0,len(li1)):
print (li1[i],end=" ")
print("\r")
# adding and element to new list
li2[2][0] = 7
# checking if change is reflected
print ("The original elements after shallow copying")
for i in range(0,len( li1)):
print (li1[i],end=" ")
print("\r")
The original elements before shallow copying
1 2 [3, 5] 4
The original elements after shallow copying
1 2 [7, 5] 4
# Deep Copying
# Deep copying is a process in which the copying process occurs recursively.
# It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original.
# In case of deep copy, a copy of object is copied in other object.
# It means that any changes made to a copy of object do not reflect in the original object.
# In python, this is implemented using “deepcopy()” function.
# importing "copy" for copy operations
import copy
# initializing list 1
li1 = [1, 2, [3,5], 4]
# using deepcopy to deep copy
li2 = copy.deepcopy(li1)
# original elements of list
print ("The original elements before deep copying")
for i in range(0,len(li1)):
print (li1[i],end=" ")
print("\r")
# adding and element to new list
li2[2][0] = 7
# checking if change is reflected
print ("The original elements after deep copying")
for i in range(0,len( li1)):
print (li1[i],end=" ")
print("\r")
print("The new different list of elements after deep copying ")
for i in range(0,len( li2)):
print (li2[i],end=" ")
The original elements before deep copying
1 2 [3, 5] 4
The original elements after deep copying
1 2 [3, 5] 4
The new different list of elements after deep copying
1 2 [7, 5] 4
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list2 = list1
print("List1 -> ",list1)
print("List2 -> ",list2)
print("id of List1 -> ",id(list1))
print("id of List2 -> ",id(list2))
list1.append([10, 11, 12])
print("List1 -> ",list1)
print("List2 -> ",list2)
List1 -> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
List2 -> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
id of List1 -> 139887637339136
id of List2 -> 139887637339136
List1 -> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
List2 -> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
#Creating a copy using Shallow Copy
import copy
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.copy(old_list)
print("Old list:", old_list)
print("New list:", new_list)
Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Adding elements to the old_list using shallow copy
old_list.append([4, 4, 4])
print("Old list: ", old_list)
print("New list:", new_list)
#Adding new nested object using shallow copy
old_list[1][1] = 'AA'
print("Old list: ", old_list)
print("New list: ", new_list)
Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 4, 4]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Old list: [[1, 2, 3], [4, 'AA', 6], [7, 8, 9], [4, 4, 4]]
New list: [[1, 2, 3], [4, 'AA', 6], [7, 8, 9]]
#Copying a list using deepcopy()
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
print("Old list: ", old_list)
print("New list:", new_list)
print("Old list id: ",id(old_list))
print("New list id: ",id(new_list))
Old list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
Old list id: 139887637332992
New list id: 139887637347520
#Adding a new nested object in the list using Deep Copy
old_list[1][0] = 'BB'
print("Old list: ", old_list)
print("New list:", new_list)
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
Copy vs Deepcopy in Dictionaries#
Below are runnable examples showing the difference between copy.copy()
(shallow copy) and copy.deepcopy()
(deep copy) when working with dictionaries.
import copy
# Example 1 — Simple Dictionary (No Nesting)
original = {'a': 1, 'b': 2}
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow['a'] = 100
deep['b'] = 200
print("Original:", original) # {'a': 1, 'b': 2}
print("Shallow:", shallow)
print("Deep:", deep)
Original: {'a': 1, 'b': 2}
Shallow: {'a': 100, 'b': 2}
Deep: {'a': 1, 'b': 200}
import copy
# Example 2 — Nested Dictionary (Shallow Copy Issue)
original = {
'name': 'Alice',
'scores': {'math': 90, 'english': 85}
}
shallow = copy.copy(original)
deep = copy.deepcopy(original)
# Modify nested value
shallow['scores']['math'] = 100
print("Original:", original) # {'name': 'Alice', 'scores': {'math': 100, 'english': 85}}
print("Deep:", deep) # {'name': 'Alice', 'scores': {'math': 90, 'english': 85}}
Original: {'name': 'Alice', 'scores': {'math': 100, 'english': 85}}
Deep: {'name': 'Alice', 'scores': {'math': 90, 'english': 85}}
import copy
# Example 3 — Nested Dict with Lists
original = {
'user': 'Bob',
'hobbies': ['reading', 'gaming']
}
shallow = copy.copy(original)
deep = copy.deepcopy(original)
# Change one item in list
shallow['hobbies'].append('coding')
print("Original:", original) # Affected (list shared with shallow)
print("Deep:", deep) # Independent
Original: {'user': 'Bob', 'hobbies': ['reading', 'gaming', 'coding']}
Deep: {'user': 'Bob', 'hobbies': ['reading', 'gaming']}
import copy
# Example 4 — Multi-Level Nested Dict
original = {
'team': {
'dev': {'Alice': ['Python', 'Django']},
'ops': {'Bob': ['Docker', 'Kubernetes']}
}
}
shallow = copy.copy(original)
deep = copy.deepcopy(original)
# Modify nested list inside 'dev'
shallow['team']['dev']['Alice'].append('Celery')
print("Original:", original) # Shared changes show up here
print("Deep:", deep) # Independent copy remains unchanged
Original: {'team': {'dev': {'Alice': ['Python', 'Django', 'Celery']}, 'ops': {'Bob': ['Docker', 'Kubernetes']}}}
Deep: {'team': {'dev': {'Alice': ['Python', 'Django']}, 'ops': {'Bob': ['Docker', 'Kubernetes']}}}
import copy
# Bonus — Visualize object identity with id()
original = {'a': {'x': [1, 2]}}
shallow = copy.copy(original)
deep = copy.deepcopy(original)
print("original['a'] id:", id(original['a']))
print("shallow['a'] id:", id(shallow['a'])) # same as original['a']
print("deep['a'] id:", id(deep['a'])) # different object
original['a'] id: 139887635989376
shallow['a'] id: 139887635989376
deep['a'] id: 139887635995456
Copy Type |
What’s Copied |
Nested Dicts/Lists |
Independent? |
---|---|---|---|
|
Only outer dictionary |
❌ Shared references |
❌ No |
|
All levels recursively |
✅ Fully copied |
✅ Yes |
Use
deepcopy
when you must ensure nested data structures are independent.
Python Lambda || Anonymous Function#
a = lambda x:x*2
# In Python, anonymous function is a function that is defined without a name. # It is defined by Lambda.
print("Double of 10 is", a(10))
Double of 10 is 20
# Making a new list by taking only the even numbers from the old list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0), my_list))
# filter function is called with all the items in the list and a new list # is returned which contains items for which the function evaluats to True.
# Output: [4, 6, 8, 12]
print(new_list)
[4, 6, 8, 12]
# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2, my_list))
# Output: [2, 10, 8, 12, 16, 22, 6, 24]
print(new_list)
[2, 10, 8, 12, 16, 22, 6, 24]
Python Assert Statement#
#Assertion without error message
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = [11,22,33]
print("Average of mark1: ", avg(mark1))
mark1 = [] # empty list gives AssertionError
print("Average of mark1: ", avg(mark1))
Average of mark1: 22.0
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[236], line 8
6 print("Average of mark1: ", avg(mark1))
7 mark1 = [] # empty list gives AssertionError
----> 8 print("Average of mark1: ", avg(mark1))
Cell In[236], line 3, in avg(marks)
2 def avg(marks):
----> 3 assert len(marks) != 0
4 return sum(marks)/len(marks)
AssertionError:
#Using assert with error message
def avg(marks):
assert len(marks) != 0, "List is empty."
return sum(marks)/len (marks)
mark2= [55,88,78,90,79]
print("Average of mark2: ", avg (mark2))
mark2 = [] # empty list gives AssertionError
print("Average of mark2: ", avg(mark2)) # AssertionError: List is empty.
Average of mark2: 78.0
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[237], line 9
6 print("Average of mark2: ", avg (mark2))
8 mark2 = [] # empty list gives AssertionError
----> 9 print("Average of mark2: ", avg(mark2)) # AssertionError: List is empty.
Cell In[237], line 3, in avg(marks)
2 def avg(marks):
----> 3 assert len(marks) != 0, "List is empty."
4 return sum(marks)/len (marks)
AssertionError: List is empty.
Python Closure#
#Defining a closure function
def print_message(message):
# This is the outer enclosing function
def print_message_inner():
# This is the nested
print(message) # messege has been captured from the enclosing scope
return print_message_inner # this got changed
# Now Let's try calling this function.
#Output: Hello
another = print_message("Hello")
another()
Hello
#Another demonstration of the closure function
def multiplier_outer(n):
def multiplier_inner(x):
return x * n
return multiplier_inner
# Multiplier of 3
times3 = multiplier_outer(3)
# Multiplier of 5
times5 = multiplier_outer(5)
# Output: 27
print(times3(9))
# Output: 15
print(times5(3))
# Output: 30
print(times5(times3(2)))
27
15
30
Python Property#
#Demonstrating the use of the property
class Temp_Celsius:
def __init__(self, temperature = 0):
print("Assigning temperature value")
self._temperature = temperature
self.temp = 4000
def convert_to_fahrenheit (self):
return (self._temperature * 1.8) + 32
def get_temperature(self):
print("Getting temperature value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting temperature value")
self._temperature = value
# property() is a built-in function, creates and returns a property object
# property (fget=None, fset=None, fdel=None, doc=None)
# property object has three methods, getter(), setter(), and delete()
# temperature = property(get_temperature, set_temperature)
# make empty property
# OR
temperature = property()
temperature = temperature.getter(get_temperature) # assign fget
temperature = temperature.setter(set_temperature) # assign fset
c = Temp_Celsius(5)
print(c.temperature)
c.temperature = 100
print(c.temperature)
print(c.__dict__)
print(c.__dict__['_temperature'])
Assigning temperature value
Getting temperature value
5
Setting temperature value
Getting temperature value
100
{'_temperature': 100, 'temp': 4000}
100
# Demonstrating the use of the property as a decorator
class Temp_Celsius:
def __init__(self, temperature = 0):
print("Assigning temperature value")
self._temperature = temperature
self.temp = 4000
def convert_to_fahrenheit (self):
return (self._temperature * 1.8) + 32
@property
def temperature(self):
print("Getting temperature value")
return self._temperature
@temperature.setter
def temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting temperature value")
self._temperature = value
c = Temp_Celsius(5)
print(c.temperature) # Getting temperature value 5
c.temperature = 100 # Setting temperature value
print(c.temperature)
print(c.__dict__)
print(c.__dict__['_temperature'])
Assigning temperature value
Getting temperature value
5
Setting temperature value
Getting temperature value
100
{'_temperature': 100, 'temp': 4000}
100
private variables in Python single underscore and double underscore#
class SingleUnderscore:
def __init__(self):
self._var = "Single underscore"
def print_var(self):
print(self._var)
class DoubleUnderscore:
def __init__(self):
self.__var = "Double underscore"
def print_var(self):
print(self.__var)
class InheritSingle(SingleUnderscore):
def change_var(self, new_value):
self._var = new_value
class InheritDouble(DoubleUnderscore):
def change_var(self, new_value):
self._DoubleUnderscore__var = new_value # name mangling # convention _classname__var
# if i used __var in setter it will not change the value of __var in the class when i use the instence of the class
# i need to create a set function in the class to change the value of __var
# class InheritDouble(DoubleUnderscore):
# def change_var(self, new_value):
# self.__var = new_value
single = InheritSingle()
double = InheritDouble()
# Access the variables
single.print_var() # prints: Single underscore
double.print_var() # prints: Double underscore
# Change the values
single.change_var("Changed single underscore")
double.change_var("Changed double underscore")
single.print_var() # prints: Changed single underscore
double.print_var() # prints: Changed double underscore
Single underscore
Double underscore
Changed single underscore
Changed double underscore
# using set function in the main class to use it when inheriting insted of using convention _classname__var while inheriting
class DoubleUnderscore:
def __init__(self):
self.__var = "Double underscore"
def print_var(self):
print(self.__var)
def set_var(self, new_value):
if isinstance(new_value, str):
self.__var = new_value
else:
raise ValueError("Invalid value, must be a string")
class InheritDouble(DoubleUnderscore):
def change_var(self, new_value):
self.set_var(new_value) # use set function to change the value of __var in the class insted of useing convention _classname__var
inh = InheritDouble()
inh.print_var()
inh.set_var("New value")
inh.print_var()
inh.change_var("New value 2")
inh.print_var()
inh.print_var()
parend_class_obj = DoubleUnderscore()
parend_class_obj._DoubleUnderscore__var = "New value 4" # we can access the __var using the convention _classname__var from the parent class only
parend_class_obj.print_var()
Double underscore
New value
New value 2
New value 2
New value 4