Com 315 Python Lecture Note 2022 1
Com 315 Python Lecture Note 2022 1
Introduction
Python is an object-oriented programming language created by Guido Rossum
in 1989. It is ideally designed for rapid prototyping of complex applications. It
has interfaces to many OS system calls and libraries and is extensible to C or
C++. The Python programming language has been used by many people like
Software Engineers, Data Analysts, Network Engineers, Mathematicians,
Accountants, Scientists, and many more. Using Python, one can solve complex
problems in less time with fewer lines of code. Similarly, many large companies
use the Python programming language, including NASA, Google, YouTube,
BitTorrent, etc.
Python is an interpreted language, which can save you considerable time during
program development because no compilation or linking is necessary. The
interpreter can be used interactively, which makes it easy to experiment with
features of the language, to write throw-away programs, or to test functions
during bottom-up program development. It is also a handy desk calculator.
The Python interpreter and the extensive standard library are freely available in
source or binary form for all major platforms from the Python Web site,
https://www.python.org/, and may be freely distributed. The same site also
contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.
Features of Python
The Python programming language has a very wide range of applications and
few of them are listed below.
A Python variable is a reserved memory location to store values and gives data
to the computer for processing. Variables can be declared by any name. Python
does not bound users to declare variable before using it. It allows users to create
variable at required time. There is no need to declare a variable in advance (or
to assign a data type to it). Assigning a value to a variable itself declares and
initializes the variable with that value. For example;
b = 15 # b is of type int
String variables can be declared either by using single or double quotes. For
example:
name = “Ahmad”
# is the same as
name = ‘Ahmad’
Also, variable assignment works from left to right. For example the variable
assignment below is not correct
15 = a
print (f)
The Output will look like:
2
1
8
A variable is a symbolic name for (or reference to) information. The variable’s
name represents what information the variable contains. They are called
variables because the represented information can change but the operations on
the variable remain the same. The rules for naming Python variables include:
x = 12
_x = 20
name = “Abdul”
the_name = “Usman”
amount = 36
myName = “Fatima”
In Python, there is a rich set of operators, and they are classified as follows.
In Python, the arithmetic operators are the operators used to perform a basic
arithmetic operation between two variables or two values. The following table
presents the list of arithmetic operations in Python along with their description.
To understand the example let's consider two variables a with value 10 and b
with value 3
COM 315 HNDCS I Page 6
Let's look at the following example code to illustration the arithmetic operators
in Python.
a = 10
b=3
print ("a + b =” a + b)
print ("a - b = “ a - b)
print ("a * b = “ a * b)
print ("a / b = “ a / b)
print ("a % b = “ a % b)
print ("a ** b = “ a ** b)
print ("a // b = “ a // b)
Assignment Statement
The data item can be a single item (e.g. a constant, another variable, or a
function reference) or it can be an expression. The data item must however, be
of the same type as the variable to which it is assigned.
In Python, the assignment operators are the operators used to assign the right-
hand side value to the left-hand side variable. The following table presents the
list of assignment operators in Python along with their description
To understand the example let's consider two variables a with value 10 and b
with value 3.
left operand
//= Floor Division Performs floor division on a //= b≈ ( a = a // b )
and Assign operators and assign
value to the left operand
In Python, the comparison operators are used to compare two values. In other
words, comparison operators are used to check the relationship between two
variables or values. The comparison operators are also known as Relational
Operators. The following table presents the list of comparison operators in
Python along with their description.
To understand the example let's consider two variables a and b with values 10
and 3.
In Python, the logical operators are used to merge multiple conditions into a
single condition. The following table presents the list of logical operators in
Python along with their description.
To understand the example let's consider two variables a with value 10 and b
with value 3.
In Python, identity operators are used to compare the memory locations of two
objects or variables. There are two identity operators in Python. The following
table presents the list of identity operators in Python along with their
description.
To understand the example let's consider two variables a with value 10 and b
with value 3
object otherwise
returns True.
Interactive Mode
The Python programming language provides a variety of built-in data types. The
type of information that Python program will use are known as types and the
language will contain many different types to help make things easier. Data
types are the classification or categorization of data items. Data types represent
a kind of value, which determine what operations can be performed on that data.
The following are the most commonly used built-in data types in Python.
This type of data type has a numeric value. The Python programming language
provides three numeric data types. They are as follows:
integer – This value is represented by int class. It contains positive and negative
whole numbers (for example, 10, 5, -1, -6, etc.). In Python there is no limit to
how long an integer value can be.
float – This value is represented by float class. It is a real number with floating
point representation. It is specified by a decimal point (for example, 0.1, -2.5,
4.00, etc.).
The function type ( ) is used to determine the type of data type. Variables of
numeric type are created when you assign value to them, for instance:
a=9 # int
b = 5.7 # float
c = 6j # complex
To verify the type of any object in Python, use the type ( ) function:
>>> print (type (a))
>>> print (type (b))
>>> print (type (c))
Output:
<class ‘int’)
<class ‘float’)
<class ‘complex’)
Type conversion (CASTINg)
We can convert from one type to another with the int ( ), float ( ), and complex (
) functions. For example:
Boolean is a data type with one of the two built-in values; true and false.
Boolean object that are equal to true are truthy (true) and those that are equal to
false are falsy (false). But non-Boolean objects can be evaluated in Boolean
context as well and determined to be true or false. It is denoted by the class
bool. Booleans represent one of the two values; true or false. In programming
there is need to know if an expression is true or false. The two values that
apply to Boolean-type data represent an ordered set with false
preceding true. Boolean type expressions are formed by
combining operands of the same type with relational operators.
These operators include: = =, !=, <, <=, > and >=. For example,
SEQUENCE TYPE
Print (‘Welcome’)
Print (“Welcome”)
When we run the above code, it produces the output as follows:
Welcome
Welcome
Tips!
The escape sequences are the special characters in string data. All the escape
sequences are prefixed with a backslash (\) character. A backslash (\) character
in a string intimates that one or more characters that follow it should be
interpreted with their special meaning only. The following table presents some
of the escape sequences that are allowed in Python.
The list is the most commonly used data type available in Python. In Python, the
list data type values are enclosed in square brackets ([ ]) and each value is
separated with comma symbol. In Python, the list data type may contain
different data type values.
roll_list = [1, 2, 3, 4, 5]
print (roll_list)
student = [1, “Usman”, "3rd Year", 86.5]
print (student)
print (type (student))
When we run the above code, it produces the output as follows:
[1, 2, 3, 4, 5]
[1, 'Usman', ‘3rd Year’, 86.5]
< class ‘list’ >
Tuple' data type in Python
The tuple is similar to list in Python. In Python, the tuple data type is
immutable. That means the tuples cannot be modified, unlike lists. In Python,
the tuples may contain different data type values. The tuples are enclosed in
parentheses. Let's look at the code to illustrate tuples in Python.
roll_list = (1, 2, 3, 4, 5)
print (roll_list)
student = (1, “Usman”, "3rd Year", 86.5)
print (student)
print (type (student))
(1, 2, 3, 4, 5)
(1, 'Usman', ‘3rd Year’, 86.5)
< class ‘tuple’ >
Syntax
<class ‘dict’>
(‘Ahmad’: ‘Python’, ‘Fatima’: ‘C Programming’)
Input and Output
Python provides numerous built-in functions that are readily available to use at
the Python prompt. Python provides methods that can be used to read and write
data. The print statement is used to print the output on the screen. It is used to
take string as input and place that string to standard output. Whatever to be
displayed on the output is placed inside the inverted commas. The expression
whose value is to be printed is placed without inverted commas. Examples are:
Example 2:
x = 25
print (‘The total number of students in HNDCS I is : ‘,
x * 6)
Developers often have a need to interact with users, either to get data or to
provide some sort of result. Most programs today use a dialog box as a way of
asking the user to provide some type of input. While Python provides two built-
in functions to read the input from the keyboard:
Example 1:
username = input (‘Please, enter username :’)
print (‘Username is : ‘, username)
The output will be:
Please, enter username: Sadiq
Username is: Sadiq
Example 2:
Python import
import math
print (math.pi)
output:
3.141592653589793
In Python, the default execution flow of a program is a sequential order. But the
sequential order of execution flow may not be suitable for all situations.
Sometimes, we may want to jump from one line to another line, we may want to
skip a part of the program, or sometimes we may want to execute a part of the
program again and again. To solve this problem, Python provides control
statements.
In Python, the control statements are the statements which will tell us that in
which order the instructions are getting executed. The control statements are
used to control the order of execution according to our requirements. Python
provides several control statements, and they are classified as follows.
i. if statement
ii. if-else statement
iii. nested if statement
iv. if-elif statement
if statement in Python
In Python, we use the if statement to test a condition and decide the execution of
a block of statements based on that condition result. The if statement checks, the
given condition then decides the execution of a block of statements. If it is True,
then the block of statements is executed and if it is False, then the block of
statements is ignored. The execution flows of if statement is as follows:
False
Condition
True
If block of statements
Normal statements
if condition:
Statement_1
Statement_2
Statement_3
...
When we define an if statement, the block of statements must be specified using
indentation only. The indentation is a series of white-spaces. Here, the number
of white-spaces is variable, but all statements must use the identical number of
white-spaces. Let's look at the following example Python code.
n =10
if n % 2 = = 0:
print (‘n is an even number’)
Output:
n is an even number
Example 2:
num = int (input ('Enter any number: '))
if (num % 5 == 0):
print ('The given number’, num, ‘ is divisible by
5')
print ('This statement belongs to if statement')
print ('This statement does not belongs to if
statement')
Output:
Output:
Enter any number : 9
This statement does not belongs to if statement
Note: In the above execution, the number 9 is not divisible by 5. So, the
condition becomes false and the if statement ignores the execution of its block
statement.
In Python, we use the if-else statement to test a condition and pick the execution
of a block of statements out of the two blocks based on that condition result.
The if-else statement checks the given condition then decides which block of
statements to be executed based on the condition result. If the condition is True,
then the true block of statements is executed and if it is False, then the false
block of statements is executed. The execution flow of if-else statement is as
follows:
if num % 2 = = 0:
else:
Output:
Enter number: 4
Example 2:
Nested if statement
Example 1: Write a Python program to determine the largest among the three
numbers
a = int (input ( ‘enter value for a: ’ ) )
b = int ( input ( ‘enter value for b : ‘ ) )
c = int ( input ( ‘enter value for c : ‘ ) )
if a > b :
if a > c :
print ( ‘The largest among the three numbers is
a:‘,a)
else :
print (‘The largest among the three numbers is
c: ‘, c )
elif b > c :
print (‘The largest among the three numbers is b : ‘, b
)
else :
print (‘The largest among the three numbers is c : ‘, c
)
In Python, when we want to test multiple conditions we can also use elif
statement.
if condition_1:
Statement_1
Statement_2
Statement_3
...
Elif condition_2:
Statement_4
Statement_5
Statement_6
...
else:
Statement_7
Statement_8
...
In the above syntax, whenever the condition_1 is True, the statements 1, 2, and
3 will be executed. If the condition_1 is False and condition_2 is True then the
statements 4, 5, and 6 will be executed. And if condition_1 and Condition_2
both are False then the statements 7 and 8 will be executed. Let's look at the
following example of Python code.
elif x > y:
print (‘x is greater than y’)
else:
print (‘x is smaller than y’)
Example 2: write a Python program to display the grade of a student based on
the marks scored. (Note: marks > = 80 = A, marks >= 65 = B, marks >= 50 = C
and marks < 50 = D)
# Example 2
marks = int (input (‘ enter the marks scored : ‘) )
if marks >= 80 :
grade = ‘A’
elif marks >= 65 :
grade = ‘B’
elif marks >= 50 :
grade = ‘C’
else :
grade = ‘D’
print (‘The total marks scored = ‘ marks)
print (‘The grade = ‘ grade)
i. while statement
while statement
The while loop used to iterate (or repeat) one or more code statements as long
as the test condition is true.
Syntax
while condition :
Statement_1
Statement_2
Statement_3
...
The execution flows of while statement is as shown in the following figure.
Example 1: Write a Python code to display the first six integer numbers
i=1
while i <= 6 :
print ( i )
i += 1
The variable used in the loop condition is the number I, which we used to count
the integers from 1 – 6. First, we initialize this number to 1. In the condition, the
code check whether i is less than or equal to 6, and if it is true, the loop body
will be executed. Then the code updates i by incrementing it by 1.
Example 2: Write a Python code to add the first ten integer numbers together
total = 0
i=1
while i <= 10 :
total += i
print (total)
i += 1
With the break statement, we can stop the loop even if the while condition is
true. For example, to exit the loop when i is 3
i=1
while i < = 6 :
print (i)
if i = = 3 :
break
i+=1
Output:
1
2
3
The while with continue statement
With the continue statement, we can stop the current iteration and continue with
the next iteration. For example, to continue to the next iteration if i is 3 is shown
below:
i=0
while i < = 6 :
i+=1
if i = = 3 :
continue
print (i)
Output:
1
2
4
5
6
The while with else statement
With the else statement we can run a block of code once when the condition is
no longer true. Example, print a message once the condition is false:
i=1
while i < 6
print ( i )
i+=1
else :
print ( ‘ i is no longer less than 6 ‘)
Output:
1
2
3
4
5
i is no longer less than 6
In Python, the for statement is used to iterate through a sequence like a list, a
tuple, a set, a dictionary, or a string. With the for loop we can execute a set of
statements once for each item in a list, tuple, or a set etc. The syntax is given
below:
Output:
1
2
4
5
Job is done !
Python code to illustrate for statement with Tuple
my_set = {1, 2, 3, 4, 5}
for value in my_set:
print (value)
print ('Job is done!')
The output will look like:
1
2
3
4
5
Job is done
P
y
t
h
o
n
P
Exercises
COM 315 HNDCS I Page 41