You are on page 1of 22

Kwame Nkrumah University of

Science & Technology, Kumasi, Ghana

Conditional and Loops

Lecture 4

Instructors:
Augustus Ababio-Donkor
&
Jack Banahene Osei(PhD)
I n t r o d u c ti o n
 Conditionals and loops are used to control the flow of a program.
They allow the computer to make decisions based on conditions or
information received, and perform a number of tasks.

 Conditional statements allow a computer program to take different action


when certain conditions are met.
 if, elif and else statements are used to define conditions in Python.
 Conditions are logical and may take two values; True or False-(Boolean)

 On the other hand, Loops are statement or block of statement that is


executed repetitively.
Python has two kinds of loops, for loop and while loop.
 A single cycle of a loop is called iterations.

www.knust.edu.gh
Lo gical Expressions
 In the flow of a program, computer may check if a certain statement is met and decide to change
the flow, terminate or continue the program.
 Logic statement is one that returns either of the two Boolean type; True or False.
 A logical statement is formed from two or more expressions which are related.
 Two or more expressions can be compared using the following relations;
Logical Relations Meaning
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equal to
!= not equal to

 Example: In[]: 2>3 # False


In[]: 5!=6 # True
In[]: 17<=78 # True
In[]: “Amina” == “Kwame” # False
www.knust.edu.gh
L o g i c a l O p e ra t o r s
 Logical operators are used to compare and connect two statements or
expression.

 The logical operators used in Python are:


Logical Operator Logical Meaning
expression
or A or B Statement is True if either A or B is True, or both
are True
and A and B Statement is True only if A and B are true.

not not A Contradict whatever A says

 Example;
 In[]: (2<4) and (59>=-5) # True
 In[]: (5.47 == 3.8) or (14<17) # True
 In[]: not (18>13) # False
 Try: not( (23==16) or (-10>-11) )
??
www.knust.edu.gh
if, elif, a n d else s t a t e m e n t s I
(2<4) and (59>=-5)

Syntax: 
Syntax: 
if (condition) :
else:
Executes this block if
Executes this block if the
the condition is true
condition is false

www.knust.edu.gh
if, elif, a n d else s t a t e m e n t s I
 The statements follow a general block syntax;
if logical_statement1:
action1
elif logical_statement2:
action2
else:
final_action

 Above statement is interpreted as; “ if statement1 is met execute action1, else


if statement2 is met execute action2, if none of the statements are met execute
the final_action”

 It is important to note the “action” statements are always indented in. Thus
action1,
action2 and final_action are indented in their respective conditions.
 Indentation can be done by pressing the Tab key. A line can also be unindented with
the
Shift+Tab keys.

 It is also necessary to close a condition with a colon (:) www.knust.edu.gh


E xa m p l e I (if-elif-elseExample.py)
”””Determine the whether the solutions to quadratic equation ax2+bx+c = 0 are distinct, similar or
complex using the determinant”””

a=float(input("what is the coefficient a? "))


b=float(input("what is the coefficient b? "))
c=float(input("what is the coefficient c? "))

d=b**2 - 4.*a*c

if d > 0.0:
print("Solutions are distinct") # action 1
elif d == 0.0:
print("Solutions are similar") # action 2
elif d < 0.0:
print("Solutions are complex") # action 3
else :
print("There is no solution") # action 4

www.knust.edu.gh
E x a m p l e II ( G ra d i n g . p y )
import numpy as np

A = "A Excellent"
B = "B Very Good"
C = "C Good"
E = "Referred, You have to sit for the exam again"
F = "F Fail"

stMarks= int(input("Enter your score in CE 257? : "))

if (stMarks >= 70 and stMarks <=100) :


print("\n Your Grade in {} is {}".format("Computer programming", A))
elif (stMarks < 69 and stMarks > 60) :
print("\n Your Grade in {} is {}".format("Computer programming", B))
elif (stMarks <= 59) and (stMarks >= 55) :
print("\n Your Grade in {} is {} ".format("Computer programming", C))
elif (stMarks <= 54) and (stMarks >= 50) :
print("\n Your Grade in {} is {} ".format("Computer programming", E))
elif (stMarks < 50 and stMarks >= 0):
print("\n Your Grade in {} is {} ".format("Computer programming", F))
else:
print("please enter a numeric value between 0 and 100")
www.knust.edu.gh
if, elif, a n d else s t a t e m e n t s II
 The conditional statement may involve either if statement, if-else statement,
if- elif statement or if-elif-else statement.

 Also, conditional statements can be nested into each other. E.g.


if logical_statement1:
action1
elif
if logical_statement2:
action2
else
if
logical_statemen
t3:
action3
# etc: there can be
many of these
else
actionn

# the nth
action www.knust.edu.gh

• If statement can be written as


E x a m p l e II ( c a t e g o r i z e C WA _ I . p y )
”””Categorize CWA into the following classes: first class, second class lower, second class upper,
third class and pass”””

print(“\n The program categorizes Cumulative Weighted Average (CWA) based on the score”)
cwa = float(input(“Input the CWA: “))

if cwa > 0: # Proceed if CWA is positive

if cwa >= 70:


print("First Class")
elif (cwa < 70) and (cwa >= 60):
print("Second Class Upper")
elif (cwa < 60) and (cwa >= 50):
print("Second Class Lower")
elif (cwa < 50) and (cwa >= 45):
print("Pass")
else:
print("Probation")
else :
print("CWA cannot be negative")

www.knust.edu.gh
Loop
 Loops are important in Python or in any other programming
language as they help you to execute a block of code repeatedly.

 You will often come face to face with situations where you would
need to use a piece of code over and over but you don't want to
write the same line of code multiple times

 For Loop

 While loop

www.knust.edu.gh
for
loop
A for loop is used for iterating over a sequence (that is either a
list, a tuple, a dictionary, a set, or a string).

www.knust.edu.gh
for
 General form of for loop
loop in Python is:
for itervar in sequence:
body

 itervar is the iteration variable used in the body, sequence represents a sequence (i.e
list, range, array, tuple or string) and body is a series of python command that is
executed for each element in sequence.

 Sequence that is created with the sole purpose of iteration is called and iterable
sequence. Such sequences can be created with the range, zip or enumerate
function.

 Loops follow similar indentation as conditional statements.


 Loops can also be nested into other loops and conditional statements.

www.knust.edu.gh
E x a m p l e III ( p r i n t N a m e s . p y )

# Iterating over a list


”””Print the name each person in the list”””
print("List Iteration") personName = [“Abena”, “Kwame”, “Akosua”, “Kwaku”]
l = [“Tables", “Chairs", “Books"]
for i in l: for i in personName:
    print(i) print(“Hello ” + i + “!”) #concatenate string
print(“Welcome to Civil 2”)

www.knust.edu.gh
for loop with else
 A for loop can have an optional else block as well. The else part is executed if the items in the sequence
used in for loop exhausts.

 The break keyword can be used to stop a for loop. In such cases, the else part is ignored

List = [2, 6, 5, 9] stName = ‘Kwame'


for i in List: marks = {‘Peggy’: 85, ‘Julius’: 76, ‘Brown’: 95}
print(i) for student in marks:
else: if student == stName:
print("No items in the List.") print(marks[student])
break
else:
print('No entry with that name found.')

www.knust.edu.gh
A p p l i c a ti o n s of fo r loop
 Example 1 ( Prints the number of odd numbers from 1 and 100, using s as
accumulator);
sum = 0 #Initialize sum
for i in range(1, 100, 2):
sum =sum + 1 #Print each the odd iterator variable
print(i, end=“ “) #Sum the number of odd numbers printed for each iteration
#(Alternative, sum += 1)
print(“\n{}”.format(sum)) #Print the final value of sum

 Example 2 ( Print all the characters in the a string. Remember that whitespace is a character);
str = “There are places I remember all my life”
for char in str:
print(char) #Print each character in the string

 Example 3 ( Print the third letters in the string str);


for i, char in enumerate(a): #enumerate function output a counter and sequence
if i%3 == 0: #counter is divisible by 3
print (char, end=“ “) #Print every third character

www.knust.edu.gh
w h i l e loop
 Loops are used in programming to repeat a specific block of code.
 In Python the while loop is used to iterate over a block of code as long as the test expression
(condition) is true.
 General form of while loop in Python is;
while logical_statement:
body
 logical_statement is a statementthat can either be True or False and body is a series of
python commands that is executed repeatedly until logical_statement becomes False.
 This mean that somewhere in the body, the truth of logical_statement must be change after
a
number of finite iterations.

 If the logical_statement remains true throughout every iteration, the program in will be
caught in an infinite loop.
 Thus, allocated memory for the program will be used up and the program will eventually
crush. www.knust.edu.gh
 Such program can be terminated by typing Ctrl + C a couple of times, in the IPython shell
w h i l e loop
 In the while loop, test expression is checked first. The body of
the loop is entered only if the test_expression evaluates to True.

 After one iteration, the test expression is checked again. This


process continues until the test_expression evaluates to False.

 The body starts with indentation and the first unindented line
marks the end.

www.knust.edu.gh
E xa m p l e IV
# # while loop
count = 0 #While loop for adding natural numbers up to
while (count < 10):   
# sum = 1+2+3+...+n
    count = count + 1
    print("Hello Class”)
# To take input from the user,
n = int(input("Enter n: "))

“””Example to illustrate the use of # initialize sum and counter


else statement with the while loop””” sum = 0
i = 1
counter = 0 while i <= n:
while counter < 3: sum = sum + i
print(“Within the loop") i = i+1 # update counter
counter = counter + 1
else: # print the sum
print(" Within else") print("The sum is", sum)

www.knust.edu.gh
E x a m p l e V ( c a t e g o r i ze C WA _ I I . p y )
”””Categorize CWA into the following classes: first class, second class lower, second class upper, third class
and pass. The program uses while loop to check input and close program”””

import sys #import this module first

print(“\nThe program categorizes Cumulative Weighted Average (CWA) based on the score”)
cwa = input(“Input a CWA: “)

while float(cwa) < 0.0 :


cwa = input(“CWA cannot be negative. Please input a positive number or enter n to exit: “)
if cwa == “n”: sys.exit() #sys.exit() function is used to close the program

cwa = float(cwa)
if cwa >= 70:
print(“First Class”)
elif (cwa < 70) and (cwa >= 60):
print(“Second Class Upper”)
elif (cwa < 60) and (cwa >=
50): print(“Second Class
Lower”)
elif (cwa < 50) and (cwa >=
40):
print(“Pass”)
else:
print(“Probation”) www.knust.edu.gh
L o o p s a n d a r r a y o p e r a ti o n s
 The two programs below are used to compare the performance of loops
(left) and array operation (right) in execution the same task (i.e. squaring
the elements in an array). time module was used to measure execution
time
import numpy as np import numpy as np
import time import time
a = np.linspace(0, 32, 10000000) # 10 a = np.linspace(0, 32, 10000000) # 10
million million
print(a) print(a)
startTime = time.process_time() startTime = time.process_time()
for i in range(len(a)): a = a*a
a[i] = a[i]*a[i] endTime = time.process_time()
endTime = time.process_time() print(a)
print(a) print(“Run time = {}
print(“Run time = {} seconds”.format(endTime-startTime))
seconds”.format(endTime-startTime))

 NumPy array operations (such as vectorization) runs much faster and


are always preferred in any case where you have to a choice.
www.knust.edu.gh
List
C omprehensions
 List comprehensions are special features of core Python for processing and construction
lists.
 They are use very often in Python coding and provide a simple, yet elegant way to
common computing task, such as loops

 General syntax is [listElement for iterVal in seq <body>]


 listElement is the expression/value which will be evaluated and placed in the list,
iterVal is the iteration variable, seq represents a sequence and <body> is an
optional element which may contain if condition.

 Example 1 (Obtain the diagonals of a 3 x 3 matrix as a list);


 In[]: A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
 In[]: diag = [A[i][i] for i in [0, 1, 2]] #the diagonal elements

 Example 2 (Get the odd elements in a list);


 In[]: y =[1,2,3,4,5,6,7,8,9]
 In[]: oddNums = [num for num in y if num%2==1]
www.knust.edu.gh

You might also like