0% found this document useful (0 votes)
161 views

Basic Python Book PDF

This document is an introduction and revision guide to Python. It covers basic topics like what Python is, how to install and set up an IDE, data types, variables, operators, built-in data structures like lists, tuples, sets and dictionaries, conditional statements like if/else and loops. It is intended to help review core Python concepts for students and was submitted by a team of authors led by Zeeshan Hameed at the Al-Khwarizmi Institute of Computer Science, University of Engineering and Technology Lahore, Pakistan in 2022.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
161 views

Basic Python Book PDF

This document is an introduction and revision guide to Python. It covers basic topics like what Python is, how to install and set up an IDE, data types, variables, operators, built-in data structures like lists, tuples, sets and dictionaries, conditional statements like if/else and loops. It is intended to help review core Python concepts for students and was submitted by a team of authors led by Zeeshan Hameed at the Al-Khwarizmi Institute of Computer Science, University of Engineering and Technology Lahore, Pakistan in 2022.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Introduction to Python (Revision Guide)

Submited By:
Farhan Anjum
Abdul Rehman
Hafiz Waleed
Muhammad Habib
Ahmed Arsam ( prof reader )
Ali Raza ( Team Leader)
Zeeshan Hameed

Senior Instructor:
Mr. Salman Mahmood Qazi
Junior Instructor:
Mr. Muhammad Owais

Al-Khwarizmi Institute of Computer Science (KICS)


University of Engineering and Technology, G.T. Road,
Lahore, Pakistan
2022
Revision Guide

DEDICATION
I dedicate all my efforts and struggles of the educational life to my dear
parents and family members; without them I am meaningless.
Also I devote the work of this Revision Guide to respectable and honorable
teachers who taught and supported me in developing my personality as a
competent professional.

Introduction to Python (Revision Guide) i


Revision Guide

ACKNOWLEDGEMENT
I am grateful to Almighty ALLAH for giving me the strength, knowledge and
understanding to complete this project. His love has been more than sufficient to keep
and sustain me.

I would like to special thanks senior Instructor Mr. Salman Mahmood Qazi (Lecturer
at Physics Department, GCU Lahore.) who helped me to the completion of this Revision
Guide.

My thanks also extend to my Junior Instructor, Mr. Muhammad Owais, (Research


Assisstant at UET Lahore) who patiently guided me through the entire course and
completion of my Revision Guide.

I also extend gratitude and appreciation to my all classmates in the department who have
taught me at one point or the other. May ALLAH continue to bless, protect and guide
them.

My profound gratitude goes to my wonderful lovely elder brother, Mr. Muhammad


Luqman for his valuable support, patience, time and guidance in seeing me to the
completion of this Data Science course.

I also wish to acknowledge the great support of my parents, siblings and friends who
have been a source of inspiration towards my academic pursuit. ALLAH blesses you all.

Zeeshan Hameed

Introduction to Python (Revision Guide) ii


Revision Guide

Table of Content
DEDICATION .......................................................................................................................................i
ACKNOWLEDGEMENT ................................................................................................................... ii
Introduction to Python ............................................................................................................................ 9

What is Python? ..................................................................................................................................9


Getting Started with Python. .............................................................................................................9
What is IDE? .......................................................................................................................................9
HOW TO INSTALL:..........................................................................................................................9
Python Comments:..............................................................................................................................9
Python Variables: ................................................................................................................................ 9
Python Data Types: ...........................................................................................................................10
Type Casting:.....................................................................................................................................10
Type Inference: .................................................................................................................................10
Python Operators:.............................................................................................................................11
Arithmetic Operators: ......................................................................................................................11
Assignment operators: ......................................................................................................................11
Logical operators: .............................................................................................................................12
Introduction to Built-In Data Types in Python ...................................................................................12

Introduction .......................................................................................................................................13
Python Sets: .......................................................................................................................................13
Characteristics ...................................................................................................................................13
Set Methods ........................................................................................................................................13
Python List .........................................................................................................................................14
Characteristics ...................................................................................................................................14
List Methods.......................................................................................................................................14
Python Tuples ....................................................................................................................................15
Characteristics ...................................................................................................................................15
Tuple Methods ...................................................................................................................................15
Python Dictionary .............................................................................................................................16
Characteristics ...................................................................................................................................16
Dictionary Methods ...........................................................................................................................16
If else & elif Conditions .........................................................................................................................18

What are Conditional Statements in Python? ................................................................................18


Introduction to Boolean Values .......................................................................................................18
Logical Operators .............................................................................................................................18
Types of logical operators.................................................................................................................18
And Operator .....................................................................................................................................18
Python supports the usual logical conditions from mathematics: ................................................18
Python if. Condition ..........................................................................................................................19

Introduction to Python (Revision Guide) iii


Revision Guide

Python if & else Conditions ..............................................................................................................19


Python if elif & else conditions.........................................................................................................19
Python Decision Make If elif & else. ................................................................................................19
Python If-Else on One Line. .............................................................................................................19
if statement .........................................................................................................................................19
if & else statement. ............................................................................................................................19
Introduction to LOOP in python ..........................................................................................................20

Loop introduction .............................................................................................................................21


What is the structure of loop ............................................................................................................21
Types of loops ....................................................................................................................................21
While Loop.........................................................................................................................................21
FOR LOOP ........................................................................................................................................24
NESTED LOOP ................................................................................................................................26
Introduction to Functions in Python ....................................................................................................27

Introduction .......................................................................................................................................27
Advantage of Function In Python....................................................................................................28
Creating a Function ..........................................................................................................................28
Calling a Function .............................................................................................................................28
Function Name ..................................................................................................................................28
Function Parameters.........................................................................................................................28
Function Arguments .........................................................................................................................28
Multiple Parameters/Arguments .....................................................................................................28
Default Arguments ............................................................................................................................29
Keyword Arguments .........................................................................................................................29
Arbitrary Arguments, *args ............................................................................................................29
The Return Statement ......................................................................................................................29
The pass Statement ...........................................................................................................................30
Passing a List as an Argument .........................................................................................................30
Recursion ...........................................................................................................................................30
PROGRAMS USING FUNCTIONS ...............................................................................................31
Lambda Function ...................................................................................................................................33

What is a Lambda Function in Python? .........................................................................................33


How a Lambda Function in Python Works ....................................................................................33
Lambda Function Examples ............................................................................................................33
Introduction to object-oriented programming....................................................................................34

Introduction .......................................................................................................................................35
Why Choose Object-oriented Programming? ................................................................................35
Encapsulation ....................................................................................................................................35
Inheritance .........................................................................................................................................35

Introduction to Python (Revision Guide) iv


Revision Guide

Abstraction ........................................................................................................................................35
Polymorphism....................................................................................................................................35
Object-Oriented Python ...................................................................................................................35
Class……............................................................................................................................................35
Class Bundles: Behavior and State ..................................................................................................35
Creation and Instantiation ...............................................................................................................36
self…… 37
Instance Methods ..............................................................................................................................37
__Init__ Constructor .............................................................................................................................37

Types of constructors : .....................................................................................................................37


Working with Class and Instance Data...........................................................................................37
Inheritance in Python .......................................................................................................................38
Create a Child Class .........................................................................................................................38
Use the super() Function...................................................................................................................39

......................................................................................................................

Introduction to Python (Revision Guide) v


Revision Guide

Introduction to Python
1𝑠𝑡 Week lectures:
Submitted to: Mr. Salman Mahmood Qazi & Muhammad Owais
Farhan Anjum
[email protected]
Python Comments:
What is Python? Comments are the non-executable chunk of the words in
Python is a high-level popular programming language. It was code, to explain the Python code.
created by Guido van Rossum, and released in 1991. Comments can be used to make the code more readable.
It is used for: Comments can be used to prevent execution when testing
web development (server-side), code.
software development, Comments start with a #, and Python will ignore them.
mathematics (Numpy, Sci-py).
Data Science and Machine Learning.
Getting Started with Python.
What is IDE?
IDE stands for Integrated Development Environment, a
software used to develop programs.
Example:
Google Colaboratory
Anaconda (Jupyter Notebook)
Pycharm.
Here, preferably, we are using the Anaconda (Jupyter
Notebook).
How to install the Anaconda? Example:
Download Anaconda. We recommend downloading # This is the comment
Anaconda's latest Python 3 version (recommended Python print ("Hello, World!")
3.5) “This is a comment” is non-executable as it’s written with #,
HOW TO INSTALL: while the lower part of the code will give output: Hello,
Install the version of Anaconda that you downloaded, World.
following the instructions on the download page. A comment does not have to be text that explains the code, it
Congratulations, you have installed Jupyter Notebook. To run can also be used to prevent Python from executing code.
the notebook. Example:
Syntax: #print("Hello,World!")
The syntax is the grammatical rules of a programing language print("Cheers, Mate!")
to write the code. In this example, the code with #, will not execute while the
Example: lower part will print Cheers, Mate!
Print (“Hello World”) Python Variables:
OUTPUT
A variable is the name of a reserved area allocated in memory.
Hello, Word In other words, it is the name of the memory location for
storing data.
Example:
A = 89
#89 is assigned to variable a.
The above-mentioned example will print the Hello World, b = "Ali"
with given syntax, #Ali is assigned to variable b.
print(a)
if we write: #show the assigned value of a
Print “Hello world” print(b)
#wrong Syntax #Show the assigned value of b
It would give a syntax error as we have not mentioned the ‘A’ is a variable whose value is 89, and ‘b’ is also a variable
proper syntax, the brackets or () are missing. having the value ALI
Variable names are case-sensitive.
Example:
A = 55 #Uppercase A is different variable
a = 55 #Lower case a is a different variable
Both are two different variables.

Introduction to Python (Revision Guide) 6


Revision Guide
Python Data Types: the value in variable is greater than the value in variable b, so
In python, data types are very important, Variables can store the condition is true.
data of different types. Type Casting:
The process of converting the value of one data type (integer,
These are the built-in Data types in Python. string, float, etc.) to another data type is called typecasting.
Literals are static values, which can be integer, float, or Example:
complex numbers. Data Type can be inferred using the function Type ().
• String Literals
• Numeric Types
• Boolean Type
String Type: Anything was written in inverted commas, the
python will take them as string data type.
Example:
A = “Pakistan”
B= “55”
In both examples, the python will take them as strings,
although 55 is numeric.
Numeric Types: The numeric data type includes integer, x= 1 #int
float, and complex. y= 2.8 #float
A = int (5) z = 1j # complex
B = float (2.5) print(type(x))
C = 4i + 5 is a complex number. #show the type of value assigned to variable x
Boolean Type: print(type(y))
Booleans represent one of two values: True or False. #show the type of value assigned to variable y
Example: print(type(z))
a = 8880 #show the type of value assigned to variable z
#assigning the value 8880 to a variable When we execute the above code, it will change the data type
of each literal, say it’ll change Int to float, float to Int, and
b = 55
complex to str.
#assigning the value 55 to variable
Type Inference:
if b > a:
When we execute the above code, it will give the data type
of each variable, for x it’ll be Int, for y it’ll be float, and z
it’ll be complex.

#check the condition if b is greater than a or not


print("b is greater than a")
#Show the output b is greater if it’s true. Python Operators:
else: Operators are used to performing operations on variables and
print("b is not greater than a") values.
#Show the output b is not greater if it’s false. There are four basic operators In Python.
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
Arithmetic Operators:
Arithmetic operators are used with numeric values to perform
common mathematical operations:
There are six basic arithmetic operations in Python:
Addition (+)
Addition operator is used to add the 2 or more value
Example
a=5
In the above example, we are comparing two variables and b = 10
checking whether the condition is true or false. As we know print (a+b)

Introduction to Python (Revision Guide) 7


Revision Guide
#Add the values of a and b gives output. #Returns the output, 5^2.
In this example, the output will be 15, as it has added both
numbers.

In this example, the output will be 25, as it is multiplied by 5


powers 2.
Subtraction (-): Assignment operators:
a=5
The assignment operator assigns the value to the given
b = 10
variable. It is represented with this sign “=”
print (a-b)
Example:
#Subtract the values of a and b gives output
x=5
In this example, the output will be 5, as it has subtracted both
y = 12
numbers.
a = “ALI”
x = x + 5, x+=5
x = x - 5, x-=5
x = x * 5, x*=5
x = x / 5, x/=5
Example
Multiplication (*): X = 0 #Initializing the value of x
a=5 while >=20: #Defining the condition
b = 10 print x
print(a*b) x=x+2,
#Multiply the values of a and b to give the output #gives the output with increment of 2.
In this example, the output will be 50, as it has multiplication
of both numbers.

Comparison operators: This operator is used to compare two


Division (/): values.
a = 100 There are six assignment operators:
b = 10 Equal to (==):
print(a/b) x=5
#Divide the values of a and b to give the output y = 10
In this example, the output will be 10, as it has multiplication Print(x==y)
of both numbers.

#compare the both variables for equal to


Modulus (%) The output will be FALSE.
a=5 Not equal (!=)
a=2 x=5
print (x % y) #Returns the remainder of the given divisor and y = 10
dividend Print(x!=y)
In this example, the output will be 1, as it gives a remainder #compare the both variables for not equal
of divided numbers. The output will be TRUE.
Greater than (>)
x=5
y = 10
Print(x>y)
#compare both variables for greater than.
Exponentiation (**):
a=5
b=2
print(a**b)

Introduction to Python (Revision Guide) 8


Revision Guide
The output will be FALSE. • OR

• NOT
AND Operator:
Example:
x=5
Less than (<): print (x > 3 and x < 10) #check the both conditions if one of
x=5 them is false, it’ll give FALSE.
y = 10 Returns True because 5 is greater than 3 AND 5 is less than
Print(x<y) 10.
#compare both variables for less than.
The output will be TRUE
Less than or equal to (<=):
x=5
y=3
print (x <= y)
OR Operator:
x=5
print (x > 3 or x < 4) #check the both conditions if one of them
is true, it’ll give TRUE.
Returns True because one of the conditions is true (5 is greater
than 3, but 5 is not less than 4)

#compare the both variables for less than equal to Returns


False because 5 is neither less than nor equal to 3
Greater than or equal to (>=):
x=5
y=3
print(x >= y) NOT Operator:
#compare the both variables for greater than equal to x=5
print(not(x > 3 and x < 10)) #check the both conditions if one
of them is false or true, it’ll reverse the result.
Returns False because not is used to reverse the result

Returns True because five is greater, neither equal to.


Logical operators:
Logical operators are used to combining two conditional
statements.
There are three basic Logical operators.
• AND

Introduction to Built-In Data Types in Python


List, Tuple, Set, and Dictionary
Name: Abdur Rahman
Date of Lecture: March 2022
Date of performance: March 2022
Date of submission: May 13, 2022
Submitted to: Sir Salman Mahmood Qazi & Sir Owais Saleem
[email protected]

Introduction elements. The order of elements in a set is undefined


In programming, data types is an important concept. Variable though it may consist of various elements.
can store different type of data and different types can do The major advantage of using a set, as opposed to a
different things. list, is that it has a highly optimized method for checking
Here we will study Set, List, Tuple, and Dictionary. whether a specific element is contained in the set.
Python Sets: Characteristics
In Python, Set is an unordered collection of data i- Sets are unordered
type that is iterable, mutable and has no duplicate
ii- Set is unindexed

Introduction to Python (Revision Guide) 9


Revision Guide
iii- There is no way to change the items in sets Output
{True, 34, 40, 'male', 'abc'}
iv- Sets cannot contain duplicate values vi- Complete Python code:
v- Sets use curly brackets. ‘{}’ # Creating an empty set
Set Methods b = set()
Let’s, consider the following set: print(type(b))
S = {1,8,2,3} ## Adding values to an empty set
i- Len(S) b.add(4)
b.add(4)
Returns 4, the length of the set. b.add(5)
ii- S.remove(8) b.add(5) # duplicate value cannot add in a set
b.add((4, 5, 6))
Update the set S and remove the 8. ## Accessing Elements(indexing)
iii- S.pop() # b.add({4:5}) # Cannot add list or dictionary to sets
print(b)
Return the arbitrary element from the set and output
return the element removed. <class 'set'>
iv- S.clear() {(4, 5, 6), 4, 5}
## Length of the Set
Empty the Set S.
print(len(b)) # Prints the length of this set
Examples
output
i- Simple Code <class 'set'>
set = {"apple", "banana", "cherry"} 3
print(set) ## Removal of an Item
# Note: the set list is unordered, meaning: the b.remove(5) # Removes 5 fromt set b
items will appear in a random order. print(b)
Output: output
<class 'set'>
{'banana', 'cherry', 'apple'}
{(4, 5, 6), 4}
ii- Duplicate values in set will ignored
# b.remove(15) # throws an error while trying to remove
set = {"apple", "banana", "cherry", "apple"} 15 (which is not present in the set)
# here apple is used twice therefore it will be print(b.pop())
ignored in output print(b)
print(set) output
output: (4, 5, 6)
{'banana', 'cherry', 'apple'} {4}
iii- Get the Length of a Set

Thisset = {"apple", "banana", "cherry"}


print(len(thisset))
output:
3
iv- Set Items - Data Types

Set items can be of any data type:


set1 = {"apple", "banana", "cherry"}
# String
set2 = {1, 5, 7, 9, 3}
# integer
set3 = {True, False, False}
# Boolean
print(set1)
print(set2)
print(set3)
output:
{'cherry', 'apple', 'banana'}
{1, 3, 5, 7, 9}
{False, True}
A set can contain different data types:
set1 = {"abc", 34, True, 40, "male"}
print(set1)

Introduction to Python (Revision Guide) 10


Revision Guide
# Creating a Set Add 9 in the end of the list and update to [1, 5, 7,
# A set is created by using curly brackets {} . 4, 8, 2, 9]
# The objects are placed inside those brackets and are iv- L1.insert(3,0)
separated by commas (, ).
pets={"dog", "cat", "rabbit"} This will add 0 at 3 index and update list to
print (pets) [1, 5, 7, 0, 4, 8, 2]
print(type(pets)) v- L1.pop(3)
Output
This will delete the element at 3 index and return
{'rabbit', 'cat', 'dog'}
its value and update list to [1, 5, 7, 8, 2]
<class 'set'>
vi- L1.remove(7)
vii-
This will remove the 7 from the list and update
# Accessing Items the list to [1, 5, 4, 8, 2]
# Unlike lists and tuples, you can NOT access the item Examples
s of a set using indexes. i- Allow Duplicate
# It is because a set is unordered and not indexed.
# However, we can use the for loop to access all its ite thislist = ["apple", "banana", "cherry", "apple",
ms one-by-one. "cherry"]
pets = {"dog", "cat", "rabbit"} print(thislist)
for pet in pets: Output
print(pet) ['apple', 'banana', 'cherry', 'apple', 'cherry']
ii- All List Methods
Output
rabbit # Create a list using []
cat a = [1, 2 , 4, 56, 6]
dog # Print the list using print() function
Python List print(a)
Lists are used to store multiple items in a single variable. Output
Lists are one of 4 built-in data types in Python used to store [1, 2, 4, 56, 6]
collections of data, the other 3 are Tuple, Set, #reverse the value of list using
and Dictionary, all with different qualities and usage. a.reverse
Lists are created using square brackets [] a.reverse()
Example: print(a)
thislist = ["apple", "banana", "cherry"] Output
print(thislist) [6, 56, 4, 2, 1]
Output #arrange the element in the list using sort
['apple', 'banana', 'cherry'] a.sort()
Characteristics print(a)
i- List items that are ordered, changeable, and allow Output
duplicate values. [1, 2, 4, 6, 56]
# Access using index using a[0], a[1], a[2]
ii- List items are indexed, the first item has index [0], print(a[2])
the second item has index [1], etc. Output
4
iii- The list is changeable, meaning that we can #update the value of list using append
change, add, and remove items in a list after it has been a.append(32)
created. print(a)
Output
Note: There are some list methods that will change the [1, 2, 4, 6, 56, 32]
order, but in general: the order of the items will not change. # Change the value of list using insert
List Methods a.insert(3,33)
Consider the following list print(a)
L1= [1,5,7,4,8,2] Output
i- L1.sort [1, 2, 4, 33, 6, 56, 32]
# We can create a list with items of different types
Update list to [1,2,4,5,7,8] c = [45, "DATA", False, 6.9]
ii- L1.reverse print(c)
Output
Update to [2, 8, 4, 7, 5, 1]
iii- L1.append(9) [45, 'DATA', False, 6.9]
iii- Storing values in list by taking data from the
user

Introduction to Python (Revision Guide) 11


Revision Guide
# storing the values of fruits by getting values from user 3 # that means, position of 8 is at index 3.
f1 = input("Enter Fruit Number 1: ") Examples
f2 = input("Enter Fruit Number 2: ") i- Access Tuple Items
f3 = input("Enter Fruit Number 3: ")
f4 = input("Enter Fruit Number 4: ") thistuple = ("apple", "banana", "cherry")
f5 = input("Enter Fruit Number 5: ") print(thistuple[1])
f6 = input("Enter Fruit Number 6: ") Output
f7 = input("Enter Fruit Number 7: ") Banana
myFruitList = [f1, f2, f3, f4, f5, f6, f7] Note: The first item has index 0.
print(myFruitList) ii- Negative Indexing
Output
Enter Fruit Number 1: apple a. Negative indexing means start from the end.
Enter Fruit Number 2: banana b. -1 refers to the last item, -2 refers to the second last
Enter Fruit Number 3: orange
item etc.
Enter Fruit Number 4: kiwi
Enter Fruit Number 5: pine apple thistuple = ("apple", "banana", "cherry")
Enter Fruit Number 6: grapes print(thistuple[-1])
Enter Fruit Number 7: peach Output
['apple', 'banana', 'orange', 'kiwi', 'pine apple', 'grapes', Cherry
'peach'] iii- Range of Indexes
Python Tuples
Tuples are used to store multiple items in a single You can specify a range of indexes by specifying where to
variable. start and where to end the range.
Tuple is one of 4 built-in data types in Python used to When specifying a range, the return value will be a new
store collections of data, the other 3 are List, Set, and tuple with the specified items.
Dictionary, all with different qualities and usage. thistuple = ("apple", "banana", "cherry", "orange", "kiwi",
A tuple is a collection that is ordered and "melon", "mango")
unchangeable. print(thistuple[2:5])
Tuples are written with round brackets (). #This will return the items from position 2 to 5.
Characteristics #Remember that the first item is position 0,
i- Tuple items are ordered, unchangeable, and allow #and note that the item in position 5 is NOT included
duplicate values. Output
('cherry', 'orange', 'kiwi')
ii- Tuple items are indexed, the first item has index [0], the Note: The search will start at index 2 (included) and end at
second item has index [1] etc. index 5 (not included).
By leaving out the start value, the range will start at the first
iii- When we say that tuples are ordered, it means that the
item:
items have a defined order, and that order will not
thistuple = ("apple", "banana", "cherry", "orange", "kiwi",
change. "melon", "mango")
iv- Tuples are unchangeable, meaning that we cannot print(thistuple[:4])
#in this code the the range start from 0 index.
change, add, or remove items after the tuple has
Output
been created.
('apple', 'banana', 'cherry', 'orange')
v- It also allows duplicates. Since tuples are indexed, they iv- Len() function
can have items with the same value. # Getting the Length of a Tuple To get the length or the
Tuple Methods number of items in a
Consider the following tuple pets = ("dog", "cat", "rabbit")
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5) print(len(pets))
i- Count() Returns the number of times a specified value # tuple, use the len() method.
Output
occurs in a tuple
3
x = thistuple.count(5) v-
print(x)
Output # combine tuple
2 pets = ("dog", "cat", "rabbit")
ii- Index() Searches the tuple for a specified value and pets1=("thaing","pakistan","lahore")
pet_3=pets+pets1
returns the position of where it was found
print(pet_3)
x = thistuple.index(8) Output
print(x) ('dog', 'cat', 'rabbit', 'thaing', 'pakistan', 'lahore')
Output

Introduction to Python (Revision Guide) 12


Revision Guide
Python Dictionary x = car.get("model")
Dictionaries are used to store data values in key:value print(x)
pairs. output
A dictionary is a collection which is ordered*, Mustang
v- items()
changeable and do not allow duplicates.
Written in {} Returns a list containing a tuple for each key value pair
As of Python version 3.7, dictionaries are ordered. In car = {
Python 3.6 and earlier, dictionaries are unordered. "brand": "Ford",
Characteristics "model": "Mustang",
i- It is mutable "year": 1964
}
ii- It is ordered x = car.items()
print(x)
iii- It cannot contain duplicate values dict_items([('brand', 'Ford'),
Output
Dictionary Methods ('model', 'Mustang'), ('year', 1964)])
Consider the following dictionary vi- keys()
A ={ “name” : “xyz”
“from” : “ABC” Returns a list containing the dictionary's keys
“marks” : [99,90,98] } car = {
i- clear() "brand": "Ford",
"model": "Mustang",
Removes all the elements from the "year": 1964
dictionary }
car = { x = car.keys()
"brand": "Ford", print(x)
"model": "Mustang", dict_keys(['brand', 'model', 'year'])
"year": 1964 vii- pop()
}
car.clear() Removes the element with the specified key
print(car) car = {
Output "brand": "Ford",
{} "model": "Mustang",
ii- copy() "year": 1964
}
Returns a copy of the dictionary car.pop("model")
car = { print(car)
"brand": "Ford", Output
"model": "Mustang", {'brand': 'Ford', 'year': 1964}
"year": 1964 viii- popitem()
}
x = car.copy() Removes the last inserted key-value pair
print(x) car = {
Output "brand": "Ford",
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964} "model": "Mustang",
iii- fromkeys() "year": 1964
}
Returns a dictionary with the specified keys and value car.popitem()
x = ('key1', 'key2', 'key3') print(car)
y=0 output
thisdict = dict.fromkeys(x, y) {'brand': 'Ford', 'model': 'Mustang'}
print(thisdict) ix- update()
Output
{'key1': 0, 'key2': 0, 'key3': 0} Updates the dictionary with the specified key-value
iv- get() pairs
car = {
Returns the value of the specified key "brand": "Ford",
car = { "model": "Mustang",
"brand": "Ford", "year": 1964
"model": "Mustang", }
"year": 1964 car.update({"color": "White"})
} print(car)

Introduction to Python (Revision Guide) 13


Revision Guide
Output "year": 1964
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': }
'White'} x = car.values()
x- values() print(x)
Examples
Returns a list of all the values in the dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x)
Output
car = {
"brand": "Ford",
"model": "Mustang",

Introduction to Python (Revision Guide) 14


Revision Guide

If else & elif Conditions


3rd Week lectures:
Submitted by: Hafiz Waleed Ahmed
Submitted to: Mr. Salman Mahmood Qazi & Muhammad Owais
[email protected]

What are Conditional Statements in Python? Python supports the usual logical conditions from
Decision-making in a programming language is automated mathematics:
using conditional statements, in which Python evaluates the Equals: a = = a
code to see if it meets the specified conditions. The conditions If the values of two operands are equal, then the
are evaluated and processed as true or false. If this is found to condition becomes true. Otherwise, it will be a False.
be true, the program is run as needed. Example: 2 = = 2
Example: This is Condition True.
That is to say, to compare two values, which is greater and Not Equals: a ! = b
which is smaller. Depend on the condition. If the values of two operands are equal, then the
Introduction to Boolean Values condition becomes false. Otherwise, it will be true.
The Python Boolean type has only two possible values True Example: 2! = 5
and False. Use Bool () function to test if a value is True or This Condition is True.
False. Less than: a < b
Logical Operators If the value of the left operand is less than the value
A logical operation is a special symbol or word that of the right operand, then the condition becomes true.
connects two or more phrases of information. Example: 2 < 5
This Condition is True.
Less than or equal to: a <= b
If the value of the left operand is less than or equal to
the value of the right operand, then the condition
becomes true.
Example: 2 <= 5
Types of logical operators This condition is True.
There are three logical operators: Greater than: a > b
And operator If the value of the left operand is greater than the
Or operator value of the right operand, then the condition
Not operator becomes true.
And Operator Example: 2 > 5
The and operator take two values, value 1 and value 2 This condition is False.
follow the table value to find the result. Greater than or equal to: a >= b
Boolean Boolean Value Result Boolean Value If the value of the left operand is greater than or equal
Value 1 2 to the value of the right operand, then the condition
becomes true.
True True True
Example: 2 <= 5
True False False
This condition is True.
False True False
Python if. Condition
False False False
A Python if statement evaluates whether a condition is equal
Or Operator
to true or false. The statement will execute a block of code if
The or Operator is similar to the and operator, but instead it
a specified condition is equal to true. Otherwise, the block of
implements the following table to find the result when given
code within the if statement is not executed.
two Value 1 and Value 2
Boolean Boolean Result Boolean Value
Value 1 Value 2
True True True
True False True
False True True
False False False
Not Operator
The not Operator take a value, looks at its Boolean value
and converts this value to its value to its Boolean
counterpart. e.g. not True gives False, and not False gives
True.

Introduction to Python (Revision Guide) 15


Revision Guide
Python if & else Conditions if & else statement.
An if & else Python statement checks whether a condition is In Python if .. else statement, if has two blocks, one
true. If a condition is true, the if statement executes. following the expression and other following the else clause.
Otherwise, the else statement executes. Here is the
Syntax:
Write a program to check whether a person is eligible for
voting or not, and accept any age from the user.

Output:

if .. elif .. else statement


Write a python code using If elif condition to make
Python if elif & else conditions. calculator that can perform +,-,/,*
The if-elif-else statement is used to conditionally execute a
statement or a block of statements. Conditions can be true or
false, execute one thing when the condition is true, something
else when the condition is false.
Python Decision Make If elif & else.

Similar Code:

Python If-Else on One Line.


In Python, you can have if-else statements on one line.To
write an if-else statement on one line, follow the conditional
expression syntax:

Our Programs:
if statement
Here is the general form of a one way if statement.
Syntax:

Introduction to Python (Revision Guide) 16


Revision Guide

Write a program to check whether a number entered by the Write a program to accept percentages from users and
user is even or odd. display them according to the following criteria.
Output:

Similar Code:

Output:
Output:

Introduction to Python (Revision Guide) 17


Revision Guide

Introduction to LOOP in python


Name: Ahmad Arsim
Date of Lecture: March 2022
Date of performance: March 2022
Date of submission: May 15, 2022
Submitted to: Sir Salman Mahmood Qazi & Sir Owais Saleem
[email protected]

Loop introduction
In computer Programming, a Loop is used to execute a
group of instructions or a block of code multiple times,
without writing it repeatedly. The block of code is executed
based on a certain condition. Loops are the control
structures of a program. Using Loops in computer
programs simplifies rather optimizes the process of coding.

What is the structure of loop


The structure of a Loop can be virtually divided into two
parts, namely the control statement, and the body. The
control statement of a Loop comprises the conditions that
have to be met for the execution of the body of the Loop.
For every iteration of the Loop, the conditions in the control
statement have to be true. The body of a Loop comprises
the block of code or the sequence of logical statements that
are to be executed multiple times.

While Loop
In most computer programming languages, a while
loop is a control flow statement that allows code to be
executed repeatedly. The while loop can be thought of
as a repeating if statement. The while construct consists
of a block of code and a condition. The condition is
evaluated, and if the condition is true, the code within
the block is executed. This repeats until the condition
becomes false. Because while loop checks the condition
before the block is executed, the control structure is
Types of loops often also known as a pre-test.
There are two types of Loops in Python, namely, The syntax of a while loop in Python programming
1. While Loop. language is
Syntax
2. For Loop while expression:
statement(s)
Nested loop Here, statement(s) may be a single statement or a block
When a Loop is written within another Loop, the control of statements.
structure is termed as a nested Loop. Q) Print Hello three time
# store value in variable

Introduction to Python (Revision Guide) 18


Revision Guide
a=0
# using while condition
while (a <3):
print('hello word ')
# increment in a
a += 1
OUTPUT
hello word
hello word
hello word

Q) print the reverse number ?


num = 10
while num >= 1:
print(num)
num= num - 1
# this will reverse the number

OUTPUT
10
9
8
7
6
Q) print the series of number from 1 to 6 5
# store value in variable 4
i=1 3
# using while condition 2
while i <6: 1
print(i) Q) print table of number
# increment in i i=1
i +=1 num = int(input("Enter any number : "))
OUTPUT while i <= 10:
1 print(num," * ",i," = ", num * i)
2 i = i+1
3
4
5
Q) print the Square of the number
num = 1
print("Numbers Squares")
while(num<=10):
# t givs tab space
print(num,"\t", num ** 2)
num = num + 1
OUTPUT
Numbers Squares
1 1
2 4
3 9
4 16 USING BREAK CONDITION
5 25 Q) Using break condition to break the program on 6?
6 36 i=1
7 49 # using while condition
8 64 while i < 10:
9 81 print (i)
10 100 # here we use a break condition
# the break condition breaks the program where the
required condition meets
if i == 6:
break

Introduction to Python (Revision Guide) 19


Revision Guide
OUTPUT num = int(input("Enter number : "))
1 L.append(num)
2 # append is used to add number in list
3 i=i+1
4 L.sort()
5 # sort is used to arrange the number
USING CONTINUE STATEMENT print("Largest number is : ", L[-1])
Q) Using Continue statement to stop at 5 and then print("Smallest number is : ", L[0])
continue to print till 10 OUTPUT
i=2 Enter number : 4
while i < 10: Enter number : 4
i +=1 Enter number : 5
if i == 5: Enter number : 6
continue Enter number : 7
print ( i) Enter number : 8
Enter number : 9
# With the continue statement we can stop the current Enter number : 4
iteration, and continue with the next
Enter number : 3
Enter number : 2
OUTPUT
Largest number is : 9
3
Smallest number is : 2
4
6
7
8
9
10
WITH ELSE STATEMENT
Q) print series from 1 to 5 using while condition
i=1
while I <6:
print(i)
i +=1
else:
Print(“I is no longer than 6”)
# print both condition
OUTPUT
1
2
3
4
5
i is no longer less than 6 Q) Find the average number?
print("Input some integers to calculate their sum and
average. Input 0 to exit.")
# after some value we press the 0 button( exit the loop)
count = 0
sum = 0.0
number = 1
while number != 0:
number = int(input("enter numbrt "))
sum = sum + number
count += 1
if count == 0:
print("Input some numbers")
else:
print("Average and Sum of the above numbers are: ",
sum / (count-1), sum)
OUTPUT
Q) Print the greatest and smaller number?
L=[] Input some integers to calculate their sum and average.
i=0 Input 0 to exit.
while(i<10): enter numbrt 5

Introduction to Python (Revision Guide) 20


Revision Guide
enter numbrt 6
enter numbrt 4
enter numbrt 7
enter numbrt 3
enter numbrt 8
enter numbrt 0
Average and Sum of the above numbers are: 5.5 33.0

Q) Print the fruits name using for loop?


fruits = ['banana' ,'apple ', 'charry' , 'orange']
for x in fruits:
print ( x)
Output
banana
apple
charry
orange

FOR LOOP
A for loop in Python is a control flow statement that is
used to repeatedly execute a group of statements as long as
the condition is satisfied. Such a type of statement is also
known as an iterative statement. Therefore, a for loop is an
iterative statement.
The statements in any Python program are always
executed from top to bottom. However, you can control the Q) Find reverse Number using For loop?
flow of execution by employing control flow statements word = input("Input a word to reverse: ")
such as a for loop. Usually, the for loop is used when we # negitive range is used for reverse purpsoe
know in advance how many times a code block needs to be for char in range(len(word) - 1, -1, -1):
executed. print(word[char], end="")
Syntax: print("\n")
for var in iterable: OUTPUT
# statements Input a word to reverse: damha
ahmad

# Program to print squares of all numbers present in


a list
Q) find the square of the given list?
for b in "Ramdan": numbers = [1, 2, 4, 6, 11, 20]
print( b) # variable to store the square of each value
OUTPUT sq = 0
R for val in numbers:
a # calculating square of each number
m sq = val * val
d # displaying the squares
a print(sq)
n OUTPUT

Introduction to Python (Revision Guide) 21


Revision Guide
1
4
16
36
121
400

CONTINUE STATEMENT
Q) prints all the numbers from 0 to 6 except 3 and 6.
for x in range(6):
if (x == 3 or x==6):
continue
print(x,end=' ')
OUTPUT
01245

Q) Print the Prime number?


num=int(input("Enter the number"))
if num>1:
for i in range(2,num):
if (num%i)==0:
print(num,"is not a prime number")
break RANGE
else: Q) Print series using range function?
print(num, "is a prime number") range(start, stop ,[step(increment)])
else: # start number from 0 to 12th number
print(num, "is not a number") # 12th number is not include
OUTPUT
Enter the number9 for x in range( 12):
9 is not a prime number print(x)
OUTPUT
0
1
2
3
4
5
6
7
USING BREAK FUNCTION 8
Q) break the function using brake function? 9
a = [ 'ali' , 'ahmad' , 'aslam'] 10
for x in a: 11
print (x)

if x == 'ahmad':

break

# break function is used to terminate thr program


OUTPUT
ali
ahmad

Q) print the range start from 2 to 10 with the


increment of 2?
# range strat from 2 with the (2) increment end at (10)

Introduction to Python (Revision Guide) 22


Revision Guide
# last number 10 is not include # loops within loops
Q) Loop within loop?
for y in range (2 , 10, 2): adj = ['red' ,'big' , 'tasty']
print (y) fruits = [ "apple" , 'banana' , 'cherry']
output
2 for x in adj:
4 for y in fruits:
6 print( x,y)
8
OUTPUT
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
Q) print the range start from 2 to 10 with the tasty banana
increment of 3? tasty cherry
for x in range (2, 10 ,3 ):
print(x)
else:
print ( 'end')
OUTPUT
2
5
8
end

Q) Loop within loop?


animal = [ 'lion' , 'cat', "dog" ]
sound = [ 'roar' , 'meow' , 'bark']

for x in animal:
# break or stop the program for y in sound:
for x in range ( 2,20,5): print ( x , y )
if x == 17: OUTPUT
break lion roar
print (x) lion meow
else: lion bark
print('ending') cat roar
OUTPUT cat meow
2 cat bark
7 dog roar
12 dog meow
dog bark
lion meow
lion bark
cat roar
cat meow
cat bark
dog roar
dog meow
dog bark

NESTED LOOP
# nested loops

Introduction to Python (Revision Guide) 23


Revision Guide
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10= 20

Q) Print the table using for loop?


# table of 2
# print table of 2
a=2
for i in range (1 , 11 , 1):
result = i*a
print ( a ,"*" ,i, "=" ,result)
OUTPUT
2*1=2
2*2=4
2*3=6

Introduction to Functions in Python


Name: Muhammad Habib
Date of Lecture: March 2022
Date of performance: March 2022
Date of submission: May 16, 2022
Submitted to: Sir Salman Mahmood Qazi & Sir Owais Saleem
[email protected]

Introduction Advantage of Function In Python


In programming, A function is a block of code or a group
of statements that performs a particular task .
Functions are the most important aspect of an application.
A function can be defined as the organized block of reusable
code, which can be called whenever required.
Python allows us to divide a large program into the basic
building blocks known as a function. The function contains the
set of programming statements in the body of function. A
function can be called multiple times to provide reusability to
the Python program.
Functions can be both built-in or user-defined.
• Built-in functions - The built-in functions are those
functions that are pre-defined in Python. i.g.
range(), print(), type(), abs(), bin() etc. There are the following advantages of Python functions.
• Using functions, we can avoid rewriting the same
• User-define functions - The user-defined functions
logic/code again and again in a program.
are those define by the user to perform the specific
task. • We can call Python functions multiple times in a
program and anywhere in a program.

• We can track a large Python program easily when it


is divided into multiple functions.

Introduction to Python (Revision Guide) 24


Revision Guide
• Reusability is the main achievement of Python def hello ():
functions. Function Parameters
A parameter is a variable declared in the function. In this
• However, Function calling is always overhead in a example, the hello() function has one parameter, the name
Python program. parameter.
def hello(name):
x = “Hello”
print(x)
Function Arguments
An argument is the value passed to the function when it is
called. You can add as many arguments as you want, just
separate them with a comma.
def hello(name):
x = “Hello”
print(x)
hello(“John”)
Creating a Function In this example, we are calling the hello() function with one
We can create a Python function using argument, "John".
by def keyword. Multiple Parameters/Arguments
To create a function, we need the following: To use multiple parameters, separate them using commas.
• The def keyword. The arguments when calling the function should also be
• A function name. separated by commas.
• Round brackets () and a semicolon : def add_nums(num1, num2):
• A function body - a group of statements. sum = num1 + num2
print(sum)
Syntax:https://www.javatpoint.com/python- add_nums (4, 3)
functionshttps://www.javatpoint.com/python- Output:
functionshttps://www.javatpoint.com/python- 7
functions
1. def my_function(parameters):
2. function_block

3. return expression
Example:
def my_function(): Note! You will get an error if you don't pass enough required
print("Hello from a function") arguments.
Note! A group of statements must have the same def add_nums (num1,num2):
indentation level, in the example above we used 3 whitespaces sum = num1 + num2
to indent the function body. print (sum)
Calling a Function # only one argument is passed and # 2 are arguments are
To call a function, use the function name followed by required
parenthesis: add_nums (4)
Examples:
def my_function():
print("Hello from a function")
my_function()
Output:
Hello from a function

Default Arguments
A function can have default arguments.
It can be done using the assignment operator (=).
Function Name If you don't pass the argument, the default argument will be
used instead.
A function name to uniquely identify the function. Here we
Example:
define a function with the name of “hello”.
def hello(name = " Paul"):

Introduction to Python (Revision Guide) 25


Revision Guide
x = "Hello" + name
print (x)
hello(" John")
hello()
Output:
Hello John
Hello Paul

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will
be passed into your function, add two asterisk: ** before the
parameter name in the function definition.
This way the function will receive a dictionary of arguments,
and can access the items accordingly:
Example:
If the number of keyword arguments is unknown, add a
double ** before the parameter name:
def my_function(**kid):
Keyword Arguments print("His last name is "+ kid["lname"])
As you may notice, the arguments passed are assigned my_function(fname = "Tobias", lname = "Refsnes")
according to their postion. Output:
When using keyword arguments, the position does not matter. His last name is Refsnes
Example:
def fruits(fruit1, fruit2, fruit3):
print("I love", fruit1)
print("I love", fruit2)
print("I love", fruit3)

fruits(fruit3 ="grapes", fruit2 ="apples", fruit1="oranges")


Output: The Return Statement
I love oranges The return statement is used at the end of the function and
I love apples returns the result of the function. It terminates the function
I love grapes execution and transfers the result where the function is called.
The return statement cannot be used outside of the function.
Syntax: return [expression_list]
Example:
def add_nums (num1, num2):
sum = num1 + num2
return sum
print (add_nums (4, 3))
Output:
7

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed
into your function, add a * before the parameter name in the
function definition.
This way the function will receive a tuple of arguments, and
can access the items accordingly:
Example: Example:
If the number of arguments is unknown, add a * before the def my_function(x):
parameter name: return 5 * x
def my_function(*kids): print(my_function(3))
print("The youngest child is "+ kids[2]) print(my_function(5))
my_function("Emil", "Tobias", "Linus") print(my_function(9))
Output: Output:
The youngest child is Linus 15
25
45

Introduction to Python (Revision Guide) 26


Revision Guide
recursion ends when the condition is not greater than 0 (i.e.
when it is 0).
def tri_recursion(k):
# Function defined “tri_recursion” with one parameter“k”.
if(k > 0):
# if condition applied to check that passed argument as “k” is
greater than 0 or not.
result = k + tri_recursion(k - 1)
# here k + tri_recursion (k - 1) store in new variable “result”
print(result)
#print the result.
else:
result = 0
The pass Statement # 0 in result if k not greater than 0.
Function definitions cannot be empty, but for some reason if return result
you have a function definition with no content, put in the pass # return statement use to return result.
statement to avoid getting an error. print("\n\nRecursion Example Results")
Example: tri_recursion(6)
def myfunction(): # function calling.
pass Output:
Passing a List as an Argument Recursion Example Results
You can send any data types of argument to a function (string, 1
number, list, dictionary etc.), and it will be treated as the same 3
data type inside the function. 6
E.g. if you send a List as an argument, it will still be a List 10
when it reaches the function: 15
Example: 21
def my_function(food): 21
for x in food:
print(x)
fruits=["apple", "banana", "cherry"]
my_function(fruits)
Output:
apple
banana
cherry

Recursion
Python also accepts function recursion, which means a
defined function can call itself. PROGRAMS USING FUNCTIONS
Recursion is a common mathematical and programming 1. Write a Python function to sum all the numbers in a list.
concept. It means that a function calls itself. This has the
benefit of meaning that you can loop through data to reach a # by defining a function.
result. def sum(numbers):
Example: # Function defined “sum” with one parameter “numbers”.
In this example, tri_recursion() is a function that we have total = 0
defined to call itself ("recurse"). We use the k variable as the # counter setting.
data, which decrements (-1) every time we recurse. The for x in numbers:

Introduction to Python (Revision Guide) 27


Revision Guide
# for loop used to access the elements of “numbers” and
store in “x” respectively
total += x
# increment of x in total with respectively.
return total
print(sum([8, 2, 3, 0, 7]))
# NOW print the function.
Output:
20

4. Write a Python function to calculate the factorial of a


number (a non-negative integer).

# by defining a function..
2. Write a Python function to multiply all the numbers in def factorial(n):
a list. # Function defined “factorial” with one parameter “n”.
if n == 0:
# by defining a function..
return 1
def multiply(numbers):
# condition applied that if passed argument n is 0 then
# Function defined “multiply” with one parameter
return 1, otherwise return 'n * (n-1)'s factorial’.
“numbers”.
else:
total = 1
return n * factorial(n-1)
# counter setting.
# Taking input by user.
for x in numbers:
n=int(input("Input a number to compute the factorial : "))
# for loop used to access the elements of “numbers” and
print(factorial(n))
store in “x” respectively.
# NOW print the function.
total *= x
Output:
# multier increment of “x” in “total” with respectively.
Input a number to compute the factorial : 6
return total
720
print(multiply([8, 2, 3, -1, 7]))
# NOW print the function by giving value '5'.
Output:
-336

5. Write a Python function to check whether a number falls


in a given range.
# by defining a function.
def test_range(n):
# Function defined “test_range” with one parameter “n”.
3. Write a Python program to reverse a string. if n in range(3,9):
# if condition applied to check whether number is in
# by defining a function.. range or not.
def reverse_str1(str1): print( " %s is in the range"%str(n))
# Function defined “test_prime” with one parameter “n”. else :
rstr1 = '' print("The number is outside from the given range.")
index = len(str1) test_range(5)
while index > 0: # NOW print the function by giving value '5'.
rstr1 += str1[ index - 1 ] Output:
index = index - 1 5 is in the range
return rstr1
print(reverse_str1('1234abcd'))
# NOW print the function by giving string.
Output:
dcba4321

Introduction to Python (Revision Guide) 28


Revision Guide
6. Write a Python function that takes a list and returns a 8. Write a Python function to create and print a list where
new list with unique elements of the first list. the values are square of numbers between 1 and 10
(both included).
# by defining a function..
def unique_list(l): # by defining a function.
# Function defined “unique_list” with one parameter “l”. def printValues():
x = [] # Function defined “printValues”.
# an empty list create and store in “x” lst = list()
for a in l: # a List create and store in variable “lst”
# for loop used to store “l” values in “a” respectively. for i in range(1,11):
if a not in x: # for loop used to access 1 to 10 numbers with “Range”
# checking, whether “a ” is in ‘List x’ or not. function.
x.append(a) lst.append(i**2) #(i*i) can also be used.
# Here .append function is used to merged list 's unique # Here .append function used to merged lst with range’
values in empty list 'x' using for loop. squares values using for loop.
return x print(lst)
print(unique_list([1,2,3,3,3,3,4,5])) printValues()
# NOW print the function. # Function calling.
Output: Output:
[1,2,3,4,5] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

7. Write a Python function to find the Max of three


numbers. 9. Write a Python function that takes a number as a
parameter and check the number is prime or not.
# by defining a function.
def numbers(n1,n2,n3): # Note : A prime number (or a prime) is a natural number
# Function defined “numbers” with three parameters greater than 1 and that has no positive divisors other than 1
“n2,n2,n3”. and itself.
if n1>n2 & n1>n3: # by defining a function..
# if n1 is greater than n2 and n3, then n1 would be print def test_prime(n):
as greater number. # Function defined “test_prime” with one parameter “n”.
print("Max is ", n1) if (n<=1):
elif n2>n1 & n2>n3: # if condition applied to check whether “n” is less than or
# if n2 is greater than n1 and n3, then n2 would be print equal to 1 or not.
as greater number. return False
print("Max is ",n2) # If “n” is less than or equal to 1 then return false.
else: elif (n==2):
# above both condition ‘if & else’ are false then n3 would return True;
be print as greater number. # if “n” is equal to 2, return true.
print("Max is ", n3) else:
numbers(3,5,9) for x in range(2,n):
# calling Function by giving values. # for loop used to access 2 to n numbers with “Range”
Output: function.
Max is 9 if(n % x==0):
# if n is divisible by x then return false.
return False
return True
# if n is not divisible by x then return true.
print(test_prime(5))
# Now print the function by giving of n value.
Output:
True

Introduction to Python (Revision Guide) 29


Revision Guide

Lambda Function
rd Week lectures:
Submitted by: Zeeshan Hameed
Submitted to: Mr. Salman Mahmood Qazi & Muhammad Owais
[email protected]

What is a Lambda Function in Python? else print("maximum value is=",z))


A lambda function is an anonymous function (i.e., defined f=int(input("enter your first number"))
without a name) that can take any number of arguments but, s=int(input("enter your second number"))
unlike normal functions, evaluates and returns only one t=int(input("enter your third number"))
expression. A lambda function in Python has the following print(max(f,s,t))
syntax: #2 Write a Python lambda function to sum all the numbers
lambda parameters: expression in a list
The anatomy of a lambda function includes three elements: [1,3,4,50]
• The keyword lambda — an analog of def in normal a=reduce(lafrom functools import reduce
functions li=mbda x,y:x+y,li) # reduce() is to take an existing
function,
• The parameters — support passing positional and print(a) #apply it cumulatively to all the items in an
keyword arguments, just like normal functions iterable, and generate a single final value
#3 Write a Python lambda function to multiply all the
• The body — the expression for given numbers in a list
parameters being evaluated with the lambda from functools import reduce
li=[1,3,4,50]
function b=reduce(lambda x,y:x*y,li)
print(b)
Note that, unlike a normal function, we don’t surround the
# 4 Write a Python program to reverse a
parameters of a lambda function with parentheses. If a lambda
string.
function takes two or more parameters, we list them with a
reverse=lambda a:a[::-1]
comma.
enter=str(input("enter a string"))
We use a lambda function to evaluate only one short
print(reverse(enter))
expression (ideally, a single-line) and only once, meaning that
#5 Write a Python lambda function to
we aren’t going to apply this function later. Usually, we pass calculate the factorial of a number (a
a lambda function as an argument to a higher-order function non-negative integer). The function
(the one that takes in other functions as arguments), such as accepts the number as an argument
Python built-in functions like from functools import reduce
• filter(), number=int(input('enter a number'))
• map(), if number<=0:
• reduce(). print("enter a positive number")
How a Lambda Function in Python Works else:
Let’s look at a simple example of a lambda function: c=reduce(lambda
lambda x: x + 1 x,y:x*y,range(1,number+1))
Lambda Function Examples print(c)
# 6 Write a Python lambda function to
# 1 Write a Python lamda function to find the Max of three
check whether a number falls in a given
numbers
range
max=lambda x,y,z:print("maximum value is=",x) if (x>=y
enter1=int(input("enter first number of
and x>=z)\
else(print("maximum value is=",y)if y>=x and y>=z
your range ")) your range "))
enter2=int(input("enter second number enter3=int(input("enter number to check

Introduction to Python (Revision Guide) 30


Revision Guide
")) case=lambda i :d.append(i) if
rang=lambda :print("given number is i.isupper() else (l.append(i) if
within range") if (enter3 in i.islower() else None)
range(enter1,enter2)) else print("number for i in enter2: # loop for iteration
is out of range") string given in input
print(rang()) case(i)
# 7 Write a Python lambda function that print('uprer',len(d))
accepts a string and calculate the print('uprer',len(l))
number of upper case letters and lower # 8 Write a Python lambda function that
case letters takes a list and returns a new list with
d=[] # to store upper case unique elements of the first list.
l=[] # to store lower case emp=[]
enter2=str(input("enter second number li=[1,2,3,4,4,4,5,6,7]
your range ")) ulist=lambda i:emp.append(i) if i not in
emp else None l=lambda x:lambda y:x+y
for i in li: first=l(5)
ulist(i) print(first(10))
print(emp) #12 Write a Python function to check
# 9 Write a Python program that accepts whether a number is perfect or not.
a hyphen-separated sequence of words as from functools import reduce
input and prints the words in a hyphen- # for enter in range(2,10000): # this
separated sequence after sorting them loop can be used to find perfact number
alphabetically. in given range
li=lambda :[n for n in str(input('enter enter = int(input("enter a number"))
a string with hyphen')).split("-")] flist = list(filter(lambda x: enter % x
l=li() == 0, range(1, enter)))
l.sort() # print(l)
print(l) fac_sum = reduce(lambda x, y: x + y,
print('-'.join(l)) flist)
#10 Write a Python program to print the if fac_sum == enter:
even numbers from a given list using print(enter, ' is a perfect number
lambda ')
w_list=[1,2,3,4,5,6] else:
li=list(filter(lambda l:l%2==0,w_list)) print(enter, 'is not a perfect
print(li) number')
#11 Write a Python program to access a
lambda inside a lambda

pass

Introduction to object-oriented programming


Ali Raza
6th Week
Submitted to Mr Salman Qazi & Muhammad Owais Saleem
[email protected]

Introduction interacting objects via their data and behavior. Python,


Object-Oriented Programming (OOP) is a programming an Object-Oriented Programming (OOP), is a way of
paradigm based on the concept of "objects" that can programming that focuses on using objects and classes
contain data and code. The data is often implemented as to design and build applications. Major pillars of Object-
attributes. Functions implement the associated code for Oriented Programming (OOP) are Inheritance,
the data and are usually referred to in object-oriented Polymorphism, Abstraction, ad Encapsulation. Object-
jargon as methods. In OOP, computer programs are Oriented Analysis(OOA) is the process of examining a
designed by being made up of objects that interact with problem, system, or task and identifying the objects and
each other via the methods. interactions between them.
Object-Oriented means directed toward objects. In other Why Choose Object-oriented Programming?
words, it means functionally directed towards modeling Python was designed with an object-oriented approach.
objects. This is one of the many techniques used for OOP offers the following advantages:
modeling complex systems by describing a collection of

Introduction to Python (Revision Guide) 31


Revision Guide

• Provides a clear program structure, which makes it Class


easy to map real-world problems and their solutions. A class is a collection of objects. A class contains the
• Facilitates easy maintenance and modification of blueprints or the prototype from which the objects are
existing code. being created. It is a logical entity that contains some
• Enhances program modularity because each object attributes and methods.
exists independently, and new features can be added class ClassName:
easily without disturbing the existing ones. # Statement-1
• Presents a good framework for code libraries where .
supplied components can be easily adapted and modified .
by the programmer. .
• Imparts code reusability # Statement-N
A class is a user-defined blueprint or prototype from
which objects are created. Classes provide a means of
bundling data and functionality together. Creating a new Class Bundles: Behavior and State
class creates a new type of object, allowing new
A class will let you bundle together the behavior and
instances of that type to be made. Each class instance can
state of an object. Observe the following diagram for
have attributes attached to it for maintaining its state.
better understanding:
Class instances can also have methods (defined by their
class) for modifying their state.

Let us understand each of the pillars of object-oriented


programming in brief:
Encapsulation
This property hides unnecessary details and makes it
easier to manage the program structure. Each object’s
implementation and state are hidden behind well-defined
boundaries and that provides a clean and simple interface
for working with them. One way to accomplish this is by
making the data private.
Inheritance
Inheritance, also called generalization, allows us to
capture a hierarchal relationship between classes and
objects. For instance, a ‘fruit’ is a generalization of
‘orange’. Inheritance is very useful from a code reuse
perspective.
Abstraction
This property allows us to hide the details and expose
only the essential features of a concept or object. For
example, a person driving a scooter knows that by
pressing a horn, the sound is emitted, but he has no idea
about how the sound is generated by pressing the horn.
Polymorphism
Polymorphism means many forms. That is, a thing or
action is present in different forms or ways. One good
example of polymorphism is constructor overloading in
classes

Object-Oriented Python
The heart of Python programming is object and OOP,
however, you need not restrict
yourself to use the OOP by organizing your code into
classes. OOP adds to the whole
design philosophy of Python and encourages a clean and
pragmatic way to programming.
OOP also enables in writing of bigger and more complex
programs.

Introduction to Python (Revision Guide) 32


Revision Guide

class MyClass():
pass
The following points are worth notable when discussing # Create first instance of MyClass
class bundles: this_obj = MyClass()
• The word behavior is identical to function – it is a print(this_obj)
piece of code that does something (or implements a # Another instance of MyClass
behavior) that_obj = MyClass()
• The word state is identical to variables – it is a place print (that_obj)
to store values within a class.
Here we have created a class called MyClass and which
• When we assert a class behavior and state together, it does not do any tasks. pass in the above code indicates
means that a class packages functions and variables. that this block is empty, that is it is an empty class
Classes have methods and attributes definition.
In Python, creating a method defines a class behavior. Let us create an instance this_obj of MyClass() class
The word method is the OOP name and print it as shown:
given to a function that is defined within a class. To sum Output
up: <__main__.MyClass object at 0x03B08E10>
Class functions is a synonym for methods <__main__.MyClass object at 0x0369D390>
Class variables are a synonym for name attributes.
Here, we have created an instance of MyClass. The hex
Class – a blueprint for an instance with exact behavior.
code refers to the address where the object is being
Object – one of the instances of the class, perform
stored. Another instance is pointing to another address.
functionality defined in the class.
Now let us define one variable inside the class
Type – indicates the class the instance belongs to
MyClass() and get the variable from the instance of that
Attribute – Any object value: object.attribute
class as shown in the following code:
Method – a “callable attribute” defined in the class
Observe the following piece of code for example: class MyClass(object):
var = 9
var = “Hello, John”
# Create first instance of MyClass
print( type (var)) # < type ‘str’> or <class 'str'>
print(var.upper()) # upper() method is called, this_obj = MyClass()
HELLO, JOHN print(this_obj.var)
# Another instance of MyClass
that_obj = MyClass()
print (that_obj.var)
Creation and Instantiation Output
The following code shows how to create our first class You can observe the following output when you execute
and then its instance. the code given above:
9
9

Introduction to Python (Revision Guide) 33


Revision Guide

self
Class methods must have an extra first parameter in the Output
method definition. We do not give a value for this haji zeshan
parameter when we call the method, Python provides it Types of constructors :
Instance Methods default constructor: The default constructor is a simple
A function defined in a class is called a method. An constructor which doesn’t accept any arguments.
instance method requires an instance in order to call it class Myclass:
and requires no decorator. When creating an instance def __init__(self):
method, the first parameter is always self. Though we print("haji zeshan")
can call it (self) by any other name, it is recommended to x=Myclass() # object of a class
use self, as it is a naming convention.
class MyClass(): parameterized constructor: constructor with
var=9 parameters is known as parameterized constructor.
def firstM(self):
print("hello, World") class myclass():
obj = MyClass() def __init__(self,aaa, bbb):
print(obj.var) self.a = aaa
obj.firstM() self.b = bbb
Output x = myclass(4.5, 3)
You can observe the following output when you execute print(x.a, x.b)
the code given above: Output
9 4.5 3
hello, World
Note that in the above program, we defined a method
Working with Class and Instance Data
with self as argument. But we cannot call the method as
We can store data either in a class or in an instance. When
we have not declared any argument to it
we design a class, we decide which data belongs to the
class MyClass(object):
instance and which data should be stored into the overall
def firstM(self): class.
print("hello, World") An instance can access the class data. If we create
print(self) multiple instances, then these instances can access their
obj = MyClass() individual attribute values as well the overall class data.
obj.firstM() Thus, a class data is the data that is shared among all the
print(obj) instances. Observe the code given below for better
Output undersanding:
You can observe the following output when you execute class cal():
the code given above: def __init__(self,a,b): # init function is
hello, World automatically called by calling class
<__main__.MyClass object at 0x036A8E10> self.a=a
<__main__.MyClass object at 0x036A8E10> self.b=b
__Init__ Constructor def add(self): # sum function
The task of constructors is to initialize(assign values) to return self.a+self.b
the data members of the class when an object of the def mul(self): # multiplication function
class is created. In Python the __init__() method is return self.a*self.b
called the constructor and is always called when an def div(self): # division function
object is created. return self.a/self.b
Syntax of constructor declaration : def sub(self): # subtraction function
def __init__(self): return self.a-self.b
# body of the constructor a=int(input("Enter first number: ")) # take values
from user
b=int(input("Enter second number: "))
Class with Constructor: # take values from user
class Myclass: obj=cal(a,b) # calling class
def __init__(self): choice=1
print("haji zeshan") while choice!=0: #loop for multiple calculation
x=Myclass() # object of a class print("0. Exit")
The __init__() function is called automatically every print("1. Add")
time the class is being used to create a new object. print("2. Subtraction")

Introduction to Python (Revision Guide) 34


Revision Guide

print("3. Multiplication") Create a class named Person,


print("4. Division") with firstname and lastname properties, and
choice=int(input("Enter choice: ")) a printname method:
if choice==1: class Person:
print("Result: ",obj.add()) def __init__(self, fname, lname):
elif choice==2: self.firstname = fname
print("Result: ",obj.sub()) self.lastname = lname
elif choice==3:
print("Result: ",obj.mul()) def printname(self):
elif choice==4: print(self.firstname, self.lastname)
print("Result: ",round(obj.div(),2))
elif choice==0: #Use the Person class to create an object, and then
print("Exiting!") execute the printname method:
else:
print("Invalid choice!!") x = Person("John", "Doe")
x.printname()
Output Output
Enter first number: 5 Johan Doe
Enter second number: 10 Create a Child Class
0. Exit To create a class that inherits the functionality from
1. Add another class, send the parent class as a parameter when
2. Subtraction creating the child class:
3. Multiplication Example
4. Division Create a class named Student, which will inherit the
properties and methods from the Person class:
Enter choice: 1
class Student(Person):
Result: 15
pass
0. Exit
1. Add Now the Student class has the same properties and
methods as the Person class.
2. Subtraction
Python pass Statement
3. Multiplication
When the pass statement is executed, nothing happens,
4. Division but you avoid getting an error when empty code is not
allowed. Empty code is not allowed in loops, function
Inheritance in Python definitions, class definitions, or in if statements.
Inheritance is the capability of one class to derive or Example
inherit the properties from another class. The benefits of Use the Student class to create an object, and then
inheritance are: execute the print name method:
• It represents real-world relationships well. x = Student("Mike", "Olsen")
x.printname()
• It provides reusability of a code. We don’t have
to write the same code again and again. Also, it # Python code to demonstrate how parent
allows us to add more features to a class without constructors
modifying it. # are called.
• It is transitive in nature, which means that if
# parent class
class B inherits from another class A, then all
class Person( ):
the subclasses of B would automatically inherit
from class A.
# __init__ is known as the constructor
Parent class is the class being inherited from, also called def __init__(self, name, idnumber):
base class. self.name = name
Child class is the class that inherits from another class, self.idnumber = idnumber
also called derived class. def display(self):
Create a Parent Class print(self.name)
Any class can be a parent class, so the syntax is the same print(self.idnumber)
as creating any other class:
Example # child class
class Employee( Person ):

Introduction to Python (Revision Guide) 35


Revision Guide

def __init__(self, name, idnumber, salary, post): class Base1():


self.salary = salary def __init__(self):
self.post = post self.str1 = "Geek1"
print("Base1")
# invoking the __init__ of the parent class
Person.__init__(self, name, idnumber) class Base2(object):
def __init__(self):
self.str2 = "Geek2"
# creation of an object variable or an instance print("Base2")
a = Employee('Rahul', 886012, 200000, "Intern")
class Derived(Base1, Base2):
# calling a function of the class Person using its def __init__(self):
instance
a.display() # Calling constructors of Base1
# and Base2 classes
Output Base1.__init__(self)
Rahul Base2.__init__(self)
886012 print("Derived")

def printStrs(self):
Add the __init__() Function print(self.str1, self.str2)
So far we have created a child class that inherits the
properties and methods from its parent.
We want to add the __init__() function to the child class ob = Derived()
(instead of the pass keyword). ob.printStrs()
The __init__() function is called automatically every
time the class is being used to create a new object. Output
Example
Base1
Base2
Add the __init__() function to the Student class:
Derived
Geek1 Geek2
class Student(Person):
def __init__(self, fname, lname): Use the super() Function
#add properties etc. Python also has a super() function that will make the
child class inherit all the methods and properties from
When you add the __init__() function, the child class
its parent:
will no longer inherit the parent's __init__() function.
Example
Note: The child's __init__() function overrides the
inheritance of the parent's __init__() function. class Student(Person):
To keep the inheritance of the def __init__(self, fname, lname):
parent's __init__() function, add a call to the super().__init__(fname, lname)
parent's __init__() function: By using the super() function, you do not have to use
Example the name of the parent element, it will automatically
class Student(Person): inherit the methods and properties from its parent.
def __init__(self, fname, lname): Add Properties
Person.__init__(self, fname, lname) Example
Now we have successfully added the __init__() Add a property called graduationyear to
function, and kept the inheritance of the parent class, the Student class:
and we are ready to add functionality in class Student(Person):
the __init__() function. def __init__(self, fname, lname):
Different forms of Inheritance: super().__init__(fname, lname)
1. Single inheritance: When a child class inherits from self.graduationyear = 2019
only one parent class, it is called single inheritance. We
saw an example above.
2. Multiple inheritance: When a child class inherits In the example below, the year 2019 should be a
from multiple parent classes, it is called multiple variable, and passed into the Student class when
inheritance. creating student objects. To do so, add another
# Python example to show the working of multiple parameter in the __init__() function:
# inheritance Example

Introduction to Python (Revision Guide) 36


Revision Guide

Add a year parameter, and pass the correct year when


creating objects: # Driver code
class Student(Person): Tom = Dogs()
def __init__(self, fname, lname, year): Tom.isMammal()
super().__init__(fname, lname) Bruno = Horses()
self.graduationyear = year Bruno.hasTailandLegs()

x = Student("Mike", "Olsen", 2019) Output


It is a mammal.
Add Methods
Example Has legs and tail
Add a method called welcome to the Student class:
class Student(Person):
If you add a method in the child class with the same
def __init__(self, fname, lname, year): name as a function in the parent class, the inheritance of
super().__init__(fname, lname) the parent method will be overridden.
self.graduationyear = year Encapsulation in Python
Encapsulation is one of the fundamental concepts in
def welcome(self): object-oriented programming (OOP). It describes the
print("Welcome", self.firstname, idea of wrapping data and the methods that work on data
self.lastname, "to the class of", within one unit. This puts restrictions on accessing
self.graduationyear) variables and methods directly and can prevent the
Example accidental modification of data. To prevent accidental
# Python program to demonstrate change, an object’s variable can only be changed by an
object’s method. Those types of variables are known
# super function
as private variables.
A class is an example of encapsulation as it
encapsulates all the data that is member functions,
class Animals: variables, etc.
define a private member prefix the member name with
# Initializing constructor double underscore “__”.
def __init__(self):
self.legs = 4 # Python program to
self.domestic = True # demonstrate protected members
self.tail = True
self.mammals = True # Creating a base class
class Base:
def isMammal(self): def __init__(self):
if self.mammals:
print("It is a mammal.") # Protected member
self._a = 2
def isDomestic(self):
# Creating a derived class
if self.domestic:
class Derived(Base):
print("It is a domestic animal.") def __init__(self):
class Dogs(Animals): # Calling constructor of
def __init__(self): # Base class
super().__init__() Base.__init__(self)
print("Calling protected member of base class: ",
def isMammal(self): self._a)
super().isMammal()
# Modify the protected variable:
class Horses(Animals): self._a = 3
def __init__(self): print("Calling modified protected member outside class: ",
super().__init__() self._a)

def hasTailandLegs(self):
obj1 = Derived()
if self.tail and self.legs == 4:
print("Has legs and tail")

Introduction to Python (Revision Guide) 37


Revision Guide

def capital(self):
print("New Delhi is the capital of India.")
obj2 = Base()
def language(self):
# Calling protected member print("Hindi is the most widely spoken language
# Can be accessed but should not be done due to convention of India.")
print("Accessing protected member of obj1: ", obj1._a)
def type(self):
# Accessing the protected variable outside
print("Accessing protected member of obj2: ", obj2._a) print("India is a developing country.")

Output: class USA():


Calling protected member of base class: 2 def capital(self):
Calling modified protected member outside class: 3 print("Washington, D.C. is the capital of USA.")
Accessing protected member of obj1: 3
Accessing protected member of obj2: def language(self):
print("English is the primary language of USA.")
Polymorphism in Python
The word polymorphism means having many forms. In def type(self):
programming, polymorphism means the same function print("USA is a developed country.")
name (but different signatures) being used for different
types. obj_ind = India()
Example of inbuilt polymorphic functions : obj_usa = USA()
for country in (obj_ind, obj_usa):
# Python program to demonstrate in-built poly- country.capital()
# morphic functions country.language()
country.type()
# len() being used for a string Output:
print(len("geeks"))
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
# len() being used for a list
print(len([10, 20, 30])) India is a developing country.
Washington, D.C. is the capital of USA.
Output: English is the primary language of USA.
5 USA is a developed country.
3

Examples of user-defined polymorphic functions : Example of inheritance


# A simple Python function to demonstrate
# Polymorphism

def add(x, y, z = 0):


return x + y+z

# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output:
5
9

Polymorphism with class methods:


The below code shows how Python can use two different
class types, in the same way. We create a for loop that
iterates through a tuple of objects. Then call the methods
without being concerned about which class type each
object is. We assume that these methods actually exist in
each class.
class India():

Introduction to Python (Revision Guide) 38


Revision Guide

Introduction to Python (Revision Guide) 39

You might also like