Basic Python Book PDF
Basic Python Book PDF
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
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.
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.
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.
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
Table of Content
DEDICATION .......................................................................................................................................i
ACKNOWLEDGEMENT ................................................................................................................... ii
Introduction to Python ............................................................................................................................ 9
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
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
Introduction .......................................................................................................................................35
Why Choose Object-oriented Programming? ................................................................................35
Encapsulation ....................................................................................................................................35
Inheritance .........................................................................................................................................35
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
......................................................................................................................
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.
• 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)
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.
Output:
Similar Code:
Our Programs:
if statement
Here is the general form of a one way if statement.
Syntax:
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:
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.
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
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
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
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
if x == 'ahmad':
break
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
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"):
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:
# 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
Lambda Function
rd Week lectures:
Submitted by: Zeeshan Hameed
Submitted to: Mr. Salman Mahmood Qazi & Muhammad Owais
[email protected]
pass
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.
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
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")
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
def hasTailandLegs(self):
obj1 = Derived()
if self.tail and self.legs == 4:
print("Has legs and tail")
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.")
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output:
5
9