Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

Com 315 Python Lecture Note 2022 1

Python
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Com 315 Python Lecture Note 2022 1

Python
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

lOMoARcPSD|37692449

COM 315 Python Lecture note 2022-1

Computer Science (Usmanu Danfodiyo University Sokoto)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)
lOMoARcPSD|37692449

COM 315: INTRODUCTION TO PYTHON PROGRAMMING


LANGUAGE

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 easy to learn powerful programming language. It has efficient


high-level data structures and a simple but effective approach to object-oriented
programming. Python’s elegant syntax and dynamic typing, together with its
interpreted nature, make it an ideal language for scripting and rapid application
development in many areas on most platforms.

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.

Python enables programs to be written compactly and readably. Programs


written in Python are typically much shorter than equivalent C, C++, or Java
programs, for several reasons:

COM 315 HNDCS I Page 1

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

 the high-level data types allow you to express complex operations in a


single statement;
 statement grouping is done by indentation instead of beginning and
ending brackets;
 no variable or argument declarations are necessary.

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 is a very popular programming language with the following


features.

 Python is easy to learn and easy to understand.


 The Python is an interpreted programming language. It executes the code
line by line
 The Python is a cross-platform programming language. It can be used
with any operating system like Windows, Linux, MAC OS, etc.
 The Python is a free and open-source programming language.
 The Python is an Object-Oriented, Procedural and Functional
programming language
 The Python is a multi-purpose programming language
 The Python is a high-level programming language
 Python has a huge Community to get help all over the globe.
 Python has a large Ecosystem of Libraries, Frameworks, and Tools to
work with it.

COM 315 HNDCS I Page 2

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

 Graphical User Interface (GUI) programming support: Graphical user


interfaces can be developed using Python, such as tkinter, etc.
 Integrated: It can be easily integrated with languages such as C++, Java,
etc.

Application Areas of Python

The Python programming language has a very wide range of applications and
few of them are listed below.

 Data analysis and data visualization


 Mobile Apps
 Desktop Applications
 Web Applications
 Game development
 Business Applications such as e-commerce and many more
 Computer Aided Design Applications
 Audio and video Applications such as Cplay, TimPlayer, etc.
 Hacking
 Machine learning and Artificial Intelligence
 Testing and more

Python basic VARIABLES

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

COM 315 HNDCS I Page 3

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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

Output: Syntax error: cannot assign to literal

In addition, Python allows assignment of a value to multiple variables in a


single statement known as multiple assignments. Multiple assignments can be
applied in two ways; either by assigning a single value to multiple variables or
by assigning multiple values to multiple variables. For examples:

1. Assigning single value to multiple variables


a = b = c = 25
print (a)
print (b)
print (c)
The Output will look like:
25
25
25
2. Assigning multiple values to multiple variables
d, e, f = 2, 1, 8
print (d)
print (e)

COM 315 HNDCS I Page 4

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

print (f)
The Output will look like:
2
1
8

Rules for naming variables

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:

i. A variable name must start with a letter or an underscore


ii. A variable name cannot start with a number
iii. A variable name can only contain alpha-numeric characters and
underscore (A – Z, 0 – 9, and _ )
iv. Variable names are case sensitive (total, Total, and TOTAL are three
different variables)
v. Python keywords cannot be used as variable names
vi. Spaces cannot be included for example, ‘my name’ as the space is treated
by Python as a separator and thus Python thinks you are defining two
different variables (‘my’ and ‘name’)

The legal variable names include:

x = 12
_x = 20
name = “Abdul”
the_name = “Usman”
amount = 36
myName = “Fatima”

COM 315 HNDCS I Page 5

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

The illegal variable names include the following:


2y = 15
your_var = “Sadiq”
total amount = 16
Python Operators

In Python, an operator is a symbol used to perform arithmetical and logical


operations. In other words, an operator can be defined as a symbol used to
manipulate the value of an operand. Here, an operand is a value or variable on
which the operator performs its task. For example, '+' is a symbol used to
perform mathematical addition operation.

Types of Operators in Python

In Python, there is a rich set of operators, and they are classified as follows.

 Arithmetic Operators ( +, -, *, /, %, **, // )


 Assignment Operators ( =, +=, -=, *=, /=, %=, **=, //= )
 Comparison Operators ( <, <=, >, >=, = =, != )
 Logical Operators ( and, or, not )
 Identity Operators ( is, is not )
 Membership Operators ( in, not in )
 Bitwise Operators ( &, |, ^, ~, <<, >> )

Let's look at each type of operators in Python

Arithmetic Operators in Python

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

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

Opera Meaning Description Example


tor
+ Addition Performs mathematical addition a + b = 13
on both side of the operator
- Subtraction Subtracts the right-hand a - b = 7
operand from the left-hand
operand
* Multiplicatio Multiplies values on both sides a * b = 30
n of the operator
/ Division Performs division by Dividing a / b =3.33335
left-hand operand by right-hand
operand
% Modulus Performs division by Dividing a % b = 1
left-hand operand by right-hand
operand and returns remainder
** Exponent Performs exponential (power) a ** b = 1000
calculation on operators
// Floor Performs division which the a // b = 3
Division digits after the decimal point
are removed. But if one of the
operands is negative, the result
is rounded away from zero
(towards negative infinity)

COM 315 HNDCS I Page 7

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

Let's look at the following example code to illustration the arithmetic operators
in Python.

Example - 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 assignment statement is a type of simple statement that is used to assign a


data item to a variable. This statement is written in the form of:

Variable = data item

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.

Assignment Operators in Python

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

COM 315 HNDCS I Page 8

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

To understand the example let's consider two variables a with value 10 and b
with value 3.

Opera Meaning Description Example


tor

= Assignment Assigns right-hand side a = 10


value to left-hand side
variable
+= Add and Adds right operand to the a += b≈ ( a = a + b )
Assign left operand and assign
the result to left operand
-= Subtract and Subtracts right operand a -= b≈ ( a = a - b )
Assign from the left operand and
assign the result to left
operand
*= Multiply and Multiplies right operand a *= b≈ ( a = a * b )
Assign with the left operand and
assign the result to left
operand
/= Division and Divides left operand with a /= b≈ ( a = a / b )
Assign the right operand and
assign the result to left
operand
%= Modulus and Takes modulus using two a %= b≈ ( a = a % b )
Assign operands and assign the
result to left operand
**= Exponent Performs exponential a **= b≈ ( a = a ** b )
and Assign calculation on operators
and assigns value to the
COM 315 HNDCS I Page 9

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

left operand
//= Floor Division Performs floor division on a //= b≈ ( a = a // b )
and Assign operators and assign
value to the left operand

Comparison Operators in Python

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.

Opera Meaning Description Example


tor
< Less Returns True if left-hand a < b (False)
than side value is smaller than
right-hand side value,
otherwise returns False.
<= Less Returns True if left-hand a <= b (False )
than or side value is smaller than
Equal to or equal to right-hand side
value, otherwise returns
False.
> Greater Returns True if left-hand a > b (True )
than side value is larger than

COM 315 HNDCS I Page 10

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

right-hand side value,


otherwise returns False.
>= Greater Returns True if left-hand a >= b (True )
than or side value is larger than
Equal to or equal to right-hand side
value, otherwise returns
False.
== Equal to Returns True if left-hand a == b (False )
side value is equal to
right-hand side value,
otherwise returns False.
!= Not Returns True if left-hand a != b (True )
equal to side value is not equal to
right-hand side value,
otherwise returns False.
Logical Operators in Python

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.

Opera Meaning Description Example


tor

and Logical Returns True if all the a < b and a > c


AND conditions are True,
otherwise returns
False.

COM 315 HNDCS I Page 11

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

Or Logical OR Returns False if all the a < b or a > c


conditions are False,
otherwise returns
True.
Not Logical Returns True if the not a > b
NOT condition is False,
otherwise returns
False.
Identity Operators in Python

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

Operat Meaning Description Example


or
Is is identical Returns True if the a is b
variables on either
side of the operator
point to the same
object otherwise
returns False.
is not is not Returns False if the a is not b
identical variables on either
side of the operator
point to the same

COM 315 HNDCS I Page 12

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

object otherwise
returns True.
Interactive Mode

When commands are read from a terminal, the interpreter is said to be in


interactive mode. In this mode it prompts for the next command with the
primary prompt, usually three greater-than signs (>>>); for continuation lines it
prompts with the secondary prompt, by default three dots (...). Continuation
lines are needed when entering a multi-line construct. As an example, take a
look at this if statement:

>>> the_world_is_flat = True


>>> if the_world_is_flat:
... print("Be careful not to fall off!")
Comments
Comments in Python start with the hash character, #, and extend to the end of
the physical line. A comment may appear at the start of a line or following
whitespace or code, but not within a string literal. A hash character within a
string literal is just a hash character.

# this is the first comment


Total = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside
quotes."
Python Data Types

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

COM 315 HNDCS I Page 13

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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.

Let's look at each built-in data type in Python.

Numeric' data type 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.).

complex – Complex number is represented by complex class. Complex


numbers are an extension of real numbers in which all numbers are expressed as
a sum of a real part and an imaginary part. That is (real part) + (imaginary part)
j. for example, 2 + 3j.

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:

COM 315 HNDCS I Page 14

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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:

i. int ( ) : This construct an integer value from an integer literal, a float


literal or a string literal (provided the string represents a whole
number). Example:
a = int (7) # gives 7
b = int (5.8) # gives 5
c = int (‘9’) # gives 9
ii. float ( ): Constructs a float number from an integer literal, a float
literal, or a string literal. Examples are :
a = float (7) # gives 7.0
b = float (5.8) # gives 5.8
c = float (‘9’) # gives 9.0
iii. complex ( ): Constructs a complex type from a wide variety of data
types including string, integer literals, and float literals. For examples:
a = complex (7) # gives 7 + 0j

COM 315 HNDCS I Page 15

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

b = complex (5.8) # gives 5.8 + 0j


c = complex (‘9’) # gives 9 + 0j
iv. str ( ): Constructs a string from a wide variety of data types including
strings, integer literals, and float literals. For examples:

a = str (‘Usman’) # gives ‘Usman’

b = str (5) # gives ‘5’

c = str (7.0) # gives ‘7.0’

Python Boolean data types

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,

Print (10 > 9)


Print (10 = = 9)
Print (10 < 9)
Output:
True
False
False

SEQUENCE TYPE

COM 315 HNDCS I Page 16

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

In Python, sequence is the ordered collection of similar or


different data types. Sequence data type allow to store multiple
values in an organized and efficient manner. There are several
sequence types in Python, which include String, List, and Tuple
data type.

String data type in Python

A string is a sequence of character data which are confined in a single quote,


double quote, or triple quote. In Python, there is no character data type a
character is a string of length one. The string data type in Python is represented
by string class (str). In Python, a string can contain as many characters as you
wish. The only limit is the system's memory. In Python, the string may also be
an empty string. You can display a string literal with the print () function, for
example:

Print (‘Welcome’)
Print (“Welcome”)
When we run the above code, it produces the output as follows:

Welcome
Welcome

Tips!

 When a string contains a single quotation as a character in it, then enclose


it with double quotes. (Example - "It's cool")
 When a string contains double quotation as a character in it, then enclose
it with single quotes. (Example - 'Today is so "hot" outside')

COM 315 HNDCS I Page 17

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

 When a string contains both double quotation and a single quotation as


characters in it, then enclose it with triple quotes. (Example - '''It's so
"hot" outside''')

Escape Sequences in Python Strings

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.

S/No. Escape Special Meaning


Sequence
1 \' single quote (') character
2 \" Double quote (") character
3 \\ backslash (\) character
4 \n ASCII Newline character
5 \t ASCII Horizontal Tab character
6 \newline Backslash and newline ignored

List data type 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.

Example - Python code to illustrate 'List' in Python

COM 315 HNDCS I Page 18

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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.

Example - Python code to illustrate 'Tuple' in Python

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 ‘tuple’ >

Set data type in Python

COM 315 HNDCS I Page 19

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

In Python, a set is a collection of an un-ordered and un-indexed data element of


different data types. In Python, the set data type elements are immutable
(duplicates are not allowed). However, set itself is mutable. Set is created with
curly brackets. Let's look at the code to illustrate set in Python.

Example 1 - Python code to illustrate 'set' in Python

student = {1, “Abdul”, "2nd Year", 2022}


print (student)
print (type (student))
When we run the above code, it produces the output as follows:

(1, 'Abdul', ‘2nd Year’, 2022)


< class ‘set’ >

Dictionary data type in Python

In Python, a dictionary is similar to list, but dictionary stores each element as a


pair of Key and Value. In list, every element is accessed using index value,
whereas in the dictionary we use, a unique key to access a value. In a dictionary,
every key and value are separated with a colon (:) and each pair is separated
with a comma (,) symbol. In Python, the dictionary data type is called 'dict'. In
Python, a dictionary has the following syntax.

Syntax

dictionary_name = {key_1: value_1, key_2: value_2, ...}

Let's look at the following example of dictionary in Python.

Example 1 - Python code to illustrate 'dictionary' in Python

COM 315 HNDCS I Page 20

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

subject_list = {“Ahmad”: “Python”, “Fatima”: “C


Programming”}
print (type (subject_list))
print (subject_list)
In the above example, the value 'Python' is accessed using its key 'Ahmad'.

When we run the above code, it produces the output as follows:

<class ‘dict’>
(‘Ahmad’: ‘Python’, ‘Fatima’: ‘C Programming’)
Input and Output

Python print () Function

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:

Print (“HNDCS I”)


print (“Computer Science Department”)
print (“Umaru Ali Shinkafi Polytechnic”)
print (“Sokoto”)

The output would look like this:


HNDCS I
Computer Science Department
Umaru Ali SHinkafi Polytechnic
Sokoto

COM 315 HNDCS I Page 21

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

Example 2:

x = 25
print (‘The total number of students in HNDCS I is : ‘,
x * 6)

The output of this code is:


The total number of students in HNDCS I is : 150

Python input from keyboard

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:

i. raw_input (prompt) – Python 2,7 uses raw_input ( ) method


ii. input (prompt) – Python 3.6 and above use the input (prompt) method

Example 1:
username = input (‘Please, enter username :’)
print (‘Username is : ‘, username)
The output will be:
Please, enter username: Sadiq
Username is: Sadiq

Example 2:

Write a Python program to calculate simple interest

COM 315 HNDCS I Page 22

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

principal = float (input (‘Enter Principal :’,))


rate = float (input (‘Enter value for Rate :’,))
time = float (input(‘Enter value for Time :’,))
si = (principal * rate * time) / 100
print (‘The simple interest =’, si)
The output will look like :
Enter Principal : 500
Enter value for Rate : 4
Enter value for Time : 2
The simple interest = 40.0

Python import

When a program grows bigger, it is a good idea to break it into different


modules. A module is a file containing Python definitions and statements.
Python modules have a file name and end with the extension .py. Definitions
inside a module can be imported to another module or the interactive interpreter
in Python. This can be achieved using the import keyword. For example, the
math module can be imported by typing import math.

import math
print (math.pi)
output:
3.141592653589793

Python Control Statements

COM 315 HNDCS I Page 23

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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.

Types of Control Statements in Python

In Python, the control statements are classified as follows.

i. Selection Control Statements ( Decision Making Statements )


ii. Iterative Control Statements ( Looping Statements )

Python Selection Control Statements (Decision Making


Statements

In Python, the selection statements are also known as Decision control


statements or branching statements. The selection statement allows a program
to test several conditions and execute instructions based on which condition
is true. Some Decision Control Statements are:

i. if statement
ii. if-else statement
iii. nested if statement
iv. if-elif statement

if statement in Python

COM 315 HNDCS I Page 24

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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

The general syntax of the if statement in Python is as follows.

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.

Python code to illustrate if statement


Example 1:

COM 315 HNDCS I Page 25

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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:

Enter any number: 15


The given number is divisible by 5
This statement belongs to if statement
This statement does not belongs to if statement
When we enter a number which is not divisible by 5, then it produces the output
as follows:

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.

COM 315 HNDCS I Page 26

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

if-else statement in Python

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:

Execution flow diagram of if-else statement

The general syntax of if-else statement in Python is as follows.


if condition:
Statement_1
Statement_2
Statement_3
...
else:
Statement_4
Statement_5

COM 315 HNDCS I Page 27

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

In the above syntax, whenever the condition is True, the statements 1, 2


and 3 will be executed. And if the condition is False then the statements 4 and 5
will be executed. Let's look at the following examples:

Python code to illustrate if-else statement

# Python code for testing whether a given number is Even


or Odd

num = int (input ('Enter any number : '))

if num % 2 = = 0:

print ('The number’, num, ‘is an even number')

else:

print ('The number’, num, ‘is an Odd number')

print (“This statement does not belongs to if statement”)

Output:

Enter number: 4

The number 4 is an even number

This statement does not belongs to if statement

Example 2:

x = int (input (‘enter value for x:’))


if x = = 0:
x +=1
else:
x-=1
print (‘the value for x =’, x)

COM 315 HNDCS I Page 28

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

Nested if statement

This is an if statement inside another if statement.


Syntax:
If test condition_1:
If test condition_2:
Statement (s)
else:
else statements
else:
else statement(s)

The flow diagram of nested if statement

COM 315 HNDCS I Page 29

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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
)

elif statement in Python

In Python, when we want to test multiple conditions we can also use elif
statement.

The general syntax of if-elif-else statement in Python is as follows:

if condition_1:
Statement_1
Statement_2
Statement_3
...
Elif condition_2:

COM 315 HNDCS I Page 30

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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.

Flow diagram of if – elif – else statement


Example 1:
x = 15
y = 12
If x = = y:
Print (‘both are equal’)
COM 315 HNDCS I Page 31

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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)

Iterative Control Statements in Python

In Python, the iterative statements are also known as looping statements or


repetitive statements. The iterative statements are used to execute a part of the
program repeatedly as long as the given condition is true. Using iterative
statements reduces the size of the code, reduces the code complexity, makes it
more efficient, and increases the execution speed. Python provides the
following iterative statements.

i. while statement

ii. for statement

COM 315 HNDCS I Page 32

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

while statement

In Python, the while statement is used to execute a set of statements repeatedly.


The while statement is also known as entry control loop statement because in
the case of the while statement, first, the given condition is verified then the
execution of statements is determined based on the condition result. Generally,
the while loop consists of three important parts; initialization, condition and the
update.

The while loop used to iterate (or repeat) one or more code statements as long
as the test condition is true.

The general syntax of a while statement in Python is as follows.

Syntax

while condition :
Statement_1
Statement_2
Statement_3
...
The execution flows of while statement is as shown in the following figure.

COM 315 HNDCS I Page 33

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

When we define a while 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 may vary, but all statements must use the identical
number of white-spaces. Let's look at the following example of Python code.

Python code to illustrate while statement count

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

COM 315 HNDCS I Page 34

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

print (total)
i += 1

The while with break statement

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

COM 315 HNDCS I Page 35

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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

for statement in Python

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:

for <iterating_variable> in <sequence> :


statement_1
statement_2
statement_3
...

COM 315 HNDCS I Page 36

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

The flow diagram of for loop


If a sequence contains an expression list, it is evaluated first. Then, the first item
in the sequence is assigned to the iterating variable. Next, the statements block
is executed. Each item in the list is assigned to iterating variable, and the
statement(s) block is executed until the entire sequence is exhausted. In Python,
for loops make this use case simple and easy by allowing you to iterate over
sequences directly.
Here is an example of a for statement which counts from 1 to 5:
for i in range (1,6) :
print ( i )
Output:
1
2
3
4
5
range is an immutable sequence type used for ranges of integers – in this case,
the range is counting from 1 – 5. The for loop will step through each of the
numbers in turn, performing the print action for each one. When the end of the
range is reached, the for loop will exit.

COM 315 HNDCS I Page 37

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

Python code to illustrate for statement with List

# Python code to illustrate for statement with List


my_list = [1, 2, 3, 4, 5]
for value in my_list:
print(value)
print('Job is done!')

When we run the above code, it produces the output as follows.

Output:
1
2
4
5
Job is done !
Python code to illustrate for statement with Tuple

# Python code to illustrate for statement with Tuple


my_tuple = (1, 2, 3, 4, 5)
for value in my_tuple:
print(value)
print('Job is done!')
Output:
1
2
4
5
Job is done !

Python code to illustrate for statement with Set


#Python code to illustrate for statement with Set
COM 315 HNDCS I Page 38

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

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

# Python code to illustrate for statement with


Dictionary
my_dictionary = {1: ‘Ahmad’, 2: 'Sadiq', 3: 'Usman',
4: 'Abdul', 5: 'Fatima'}
for key, value in my_dictionary.items( ) :
print ({key} ’-->’ {value})
print ('Job is done!')
When we run the above code, it produces the output as follows.
Output:
1 ---> Ahmad
2 ---> Sadiq
3 ---> Usman
4 ---> Abdul
5 ---> Fatima
Job is done !
Python code to illustrate for statement with String

# Python code to illustrate for statement with String

COM 315 HNDCS I Page 39

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

for item in 'Python' :


print (item)
When we run the above code, it produces the output as follows.
Output:
P
y
t
h
o
n
Python code to illustrate for statement with Range
function
# Python code to illustrate for statement with Range
function
for value in range (1, 6) :
print (value)

When we run the above code, it produces the output as follows.


The output will look like:
1
2
3
4
5
In Python, the else clause can be used with a for statement. The else block will
be executed whenever the for statement does not terminate with a break
statement. But, if the for loop is terminated with a break statement then else
block doesn't execute.

Python code to illustrate for statement with else clause


# Here, else block gets executed because the break
statement does not execute

COM 315 HNDCS I Page 40

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

for item in 'Python' :


if item = = 'x':
break
print (item)
else :
print ('else block says for is successfully completed!')
When we run the above code, the else block is gets executed because the break
statement does not execute. It produces the output as follows.

P
y
t
h
o
n

Python code to illustrate for statement with else clause


# Here, else block will not be executed because the break
statement terminates the loop
for item in 'Python' :
if item = = 'y':
break
print (item)
else :
print ('else block says for is successfully completed!')
When we run the above code, the else block will not be executed because the
break statement terminates the loop. It produces the output as follows.

P
Exercises
COM 315 HNDCS I Page 41

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

1. Write a program to find the area of a circle, given that the


area of a circle is pi*r2

2. Evaluate the following expressions, giving that a = 6, b =


5, and c = 2.
i -5 * (781 % 3) + 4 * (1.6 + 2.9 / 2) – ( (19 // 5) % 2)
ii. 4 * ( ( a % 5) * (4 + ( b – 3))) / ((c + 2) **2 )
iii. NOT FLAG AND (((P * Q) > R) OR ((P + Q) < R))
where P = 5.0, Q = 6.0, R = 8.0 and FLAG = True
vi. Suppose A = 4, B = 7 and C = 2, find the values of D
and M, given that
D = NOT (A + B > 12) OR (B – A < 2)
M = (A < B) AND (B < C) OR (B = A)

3. Write a program that reads the marks of a student and


displays PASS or FAIL. It displays FAIL if marks are less
than 40 else display PASS.

4. Write a program that reads the students ‘registration


number & his GPA and then print a message according to
class of his GPA.

5. Write a program that reads two integer numbers and print


the maximum number among them.

6. Write an appropriate IF – THEN – ELSE statement for the


following:
Test the value of the variable hours. If hours is less than or
equal to 40, assign 4.50 to pay and assign “Regular” to
the variable status. If pay exceeds 40, assign 6.25 to pay
and assign “overtime” to status.

7. Write a program that will calculate the discount and


amount to be paid by the customer, given that if the sales

COM 315 HNDCS I Page 42

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)


lOMoARcPSD|37692449

is less than N50,000 then discount is 5% of the sales


otherwise discount is 10%.

8. Write a program that calculates the sum as well as the


average score of 10 students in a class using for-loop
statement.

9. Write a program that reads the rate of pay per hour of an


employee and reads the hours worked using while-loop
statement. Calculates the gross wage and display the
output on the screen.

10. Write a program that reads the score of 10 subjects of 20


students. Calculte the sum of scores, and display the
names and average.

COM 315 HNDCS I Page 43

Downloaded by oladele philip anuoluwapo (oladelephilipanuoluwapo@gmail.com)

You might also like