KEMBAR78
My Project | PDF | Control Flow | Data Type
0% found this document useful (0 votes)
3 views32 pages

My Project

Course material for python programming language

Uploaded by

alepikinsamson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views32 pages

My Project

Course material for python programming language

Uploaded by

alepikinsamson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

lOMoARcPSD|51300743

NCC 316: 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 Alanguage, 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:
• 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.
lOMoARcPSD|51300743

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.
• 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
lOMoARcPSD|51300743

• 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
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


lOMoARcPSD|51300743

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)
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 _ )
lOMoARcPSD|51300743

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” 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 ( =, +=, -=, *=, /=, %=, **=,
//= )
lOMoARcPSD|51300743

• 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
OperatorMeaning Description Example
+ Addition Performs mathematical addition on both side
a + b = 13
of the operator
- SubtractionSubtracts the right-hand operand from the
a-b=7
left-hand operand
* Multiplication Multiplies values on both sides of the a*
b = 30
operator
/ Division Performs division by Dividing left-hand a/
b =3.33335
operand by right-hand operand
% Modulus Performs division by Dividing left-hand
%b=1
operand by right-hand operand and returns
remainder
lOMoARcPSD|51300743

** ExponentPerforms exponential (power) calculation on


a ** b = 1000
operators
// Floor DivisionPerforms division which the digits after
the a // b = 3
decimal point are removed. But if one of the
operands is negative, the result is rounded
away from zero (towards negative infinity)
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 righthand side value to the left-hand side
lOMoARcPSD|51300743

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.
OperatorMeaning Description Example

= Assignment Assigns right-hand side a = 10


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

//= Floor Division Performs floor division on a //= b≈ ( a =


and operators and assign value a // b )
Assign 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.
Operat Meaning Description Example
o
r
< Less than a<b
Returns True if left-hand
(False)
side value is smaller than
right-hand side value,
otherwise returns False.
<= Less than Returns True if left-hand a <= b
or side value is smaller than (False )
Equal to or equal to right-hand side
value, otherwise returns
False.
> Greater a>b
Returns True if left-hand
than (True )
side value is larger than
right-hand side value,
otherwise returns False.
>= Greater Returns True if left-hand a >= b
than or side value is larger than or (True )
Equal to equal to right-hand side
value, otherwise returns
False.
== Equal to Returns True if left-hand a == b
side value is equal to (False )
right-hand side value,
lOMoARcPSD|51300743

otherwise returns False.


!= Not equal to Returns True if left-hand
side value is not equal to right-hand side
value, otherwise returns False.
Logical Operators in Python
a != b (True ) 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.
Operato Meaning Description Example
r
and Logical AND a < b and
Returns True if all the
a>c
conditions are True,
otherwise returns
False.
Or Logical OR a < b or a
Returns False if all the >c
conditions are False,
otherwise returns True.

Not Logical NOT Returns True if the not a > b


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
OperatorMeaning Description Exam
ple
Returns True if the
Is is identical variables a is b
lOMoARcPSD|51300743

on either side of the


operator point to the
same object otherwise
returns False.
is not is not identical Returns False if the a is not b
variables on
either side of the
operator point to
the same 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
lOMoARcPSD|51300743

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.

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:
a =9 # int
b = 5.7 # float
c = 6j # complex
To verify the type of any object in Python, use the type ( )
function:
lOMoARcPSD|51300743

>>> 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 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
lOMoARcPSD|51300743

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
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")
lOMoARcPSD|51300743

• When a string contains double quotation as a character


in it, then enclose it with single quotes. (Example -
'Today is so "hot" outside')
• 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 Sequence Special Meaning
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
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
lOMoARcPSD|51300743

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
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
subject_list = {“Ahmad”: “Python”, “Fatima”: “C
Programming”}
lOMoARcPSD|51300743

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 Polytechni”) print
(“Sokoto”)
The output would look clike this:
HNDCS I
Computer Science Department
Umaru Ali SHinkafi Polytechnic
Sokoto
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 builtin
functions to read the input from the keyboard:
lOMoARcPSD|51300743

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
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
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
lOMoARcPSD|51300743

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

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:
lOMoARcPSD|51300743

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:
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')
lOMoARcPSD|51300743

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.
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:
lOMoARcPSD|51300743

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

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:
lOMoARcPSD|51300743

x +=1
else:
x-=1
print (‘the value for x =’, x)
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)

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:
Example 1: x = 15
lOMoARcPSD|51300743

y = 12
If x = = y:
Print (‘both are equal’)
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
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.
lOMoARcPSD|51300743

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.

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
lOMoARcPSD|51300743

total = 0 i =
1 while i <=
10 : total
+= i
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 :
bre
ak 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
lOMoARcPSD|51300743

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
...

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) :
lOMoARcPSD|51300743

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.
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
my_set = {1, 2, 3, 4,
5} for value in
my_set: print (value)
print ('Job is done!')
lOMoARcPSD|51300743

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 ---> Usman4 ---> Abdul
5 ---> Fatima
Job is done !
Python code to illustrate for statement with String
# Python code to illustrate for statement with String
for item in 'Python' :
print (item)
When we run the above code, it produces the output as
follows.
Output: P y
t

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)
lOMoARcPSD|51300743

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
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

Exercises

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


the area of a circle is pi*r2
lOMoARcPSD|51300743

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 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.
lOMoARcPSD|51300743

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.

You might also like