Professional Documents
Culture Documents
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.
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<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
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.
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"
# the nth
action www.knust.edu.gh
print(“\n The program categorizes Cumulative Weighted Average (CWA) based on the score”)
cwa = float(input(“Input the CWA: “))
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.
www.knust.edu.gh
E x a m p l e III ( p r i n t N a m e s . p y )
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
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
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.
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: "))
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”””
print(“\nThe program categorizes Cumulative Weighted Average (CWA) based on the score”)
cwa = input(“Input a CWA: “)
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))