Lab 13 Manual
Lab 13 Manual
Muhammad Umar
Javed
University of Wah
Lab 13 Manual
Applications of Information and Communication
Technologies
1|P age
Lab13| Dr. Muhammad Umar
Javed
Table of Contents
Task List.............................................................................................................................................
Task-1 Introduction ......................................................................................................................3
Task-2 Utilize Python’s input() function .........................................................................................3
Task-3 Use if, else if, and else selection structures ...........................................................................6
Task-4 Flow Chart .......................................................................................................................13
Task-5 For Loop..........................................................................................................................16
Task-6 While Loop .....................................................................................................................19
Task-7 Break and Continue ..........................................................................................................22
Task-8 Tasks ..............................................................................................................................22
2|P age
Lab13| Dr. Muhammad Umar
Javed
Week-14
User Input
To begin this chapter, Python's input() function is discussed. Python can be used to ask users for input.
The input entered by a user can be saved to a variable and used in subsequent parts of the program. The
syntax of Python's input() function is below:
var = input('message')
Where var is the variable that stores the user's input and 'message' is the message the user sees at the
prompt. A string enclosed in quotes, like 'message', needs to be passed as an input argument to the
input() function. Let's ask a user for their age:
In [1]:
age = input('how old are you? ')
\how old are you? 9
Since the user's input is assigned to a variable, further operations can be run on it. Now, let's print the
user's age back to them. This can be accomplished with an f string. Note the f' ' inserted before the
string. A set of curly braces { } surrounds the variable's name and the variable's value is printed back to
the user.
In [2]:
age = input('how old are you? ')
3|P age
Lab13| Dr. Muhammad Umar
Javed
print(f'you are {age} years old')
how old are you? 9
you are 9 years old
Let's try another example. We will we ask the user for the base and height of a triangle and print
out the area of the triangle.
But, there is a problem with the approach below. The code block does not run because a common
error is present.
In [3]:
b = input('base of triangle: ')
h = input('height of triangle: ')
A = b*h /2
print(f'The area of the triangle is: {A}')
base of triangle: 5
height of triangle: 2
--------------------------------------------------------------------------TypeError Traceback (most recent call last)
<ipython-input-3-c9cb8f02e604> in <module>
1 b = input('base of triangle: ')
2 h = input('height of triangle: ')
----> 3 A = (1/2)*b*h
4 print(f'The area of the triangle is: {A}')
TypeError: can't multiply sequence by non-int of type 'float'
The previous section of code returns an error because of the data type of the variables b and h.
We can investigate b and h's data type with
Python's type() function.
In [4]:
b = input('base of triangle: ')
h = input('height of triangle: ')
print(f'b and h are of type: {type(b)}, {type(h)}')
base of triangle: 5
height of triangle: 2
b and h are of type: <class 'str'>, <class 'str'>
Notice both b and h are strings, even though the numbers 5 and 2 were entered as input. The output of
the input() function is always a string, even if the user enters a number.
4|P age
Lab13| Dr. Muhammad Umar
Javed
To complete the area calculation, b and h first need to be converted to floats using Python's float()
function, then the mathematical operation will run without error: In [5]:
b = input('base of triangle: ')
h = input('height of triangle: ')
A = (1/2)float(b)float(h)
print(f'The area of the triangle is: {A}')
base of triangle: 5
height of triangle: 2
The area of the triangle is: 5.0
Now that you are familiar with Python's input() function, let's utilize a user's input to decide which
lines of code will run. The concept of an selection statement is introduced the next section.
Selection Statements
Selection statements are used in programming to select particular blocks of code to run based on a logical
condition. The primary selection statements in Python are:
• if
• else
• elif
• try
• except
So far in this text, all of the Python code has either been strictly linear or linear and include functions.
A strictly linear program is a program that runs top to bottom. Every line of code in a linear program is
executed. In a linear program with functions, the program still runs head to base, but the program takes
side excursions to execute functions on the way down.
If this next couple chapters, you learn to write programs non-linearly. Non-linear programs do not
run every line of code top to bottom. In non-linear programs, sections of code may not run based on
selection statements like if and try. Non linear programs can include loops. Inside loops are sections
of code that run multiple times. Loops are defined by repetition structures like for loops and
while loops.
5|P age
Lab13| Dr. Muhammad Umar
Javed
<code to run>
The keyword if begins the statement. Following if, a logical condition must to be included. A logical
condition is an variable or expression that can be evaluated as True or False. An example of a logical
condition is a<5. The logical condition a<5 returns True if a is less than 5. Otherwise, if a is 5 or greater
a<5 returns False. Following the logical condition, a colon : is required. After the if-statement, a section
of code to run when the condition is True is included. The section of <code to run> must be indented and
every line in this section of code must be indented the same number of spaces. By convention, four
space indentation is used in Python. Most Python code editors, including Jupyter notebooks, indent code
after if-statements automatically four spaces.
The section of code below demonstrates an if-statement in Python:
In [1]:
a=2
if a<5:
print('less than five')
less than five
In the first line of code in the example above, the variable a is assigned the value 2. The second line of
code is the if-statement. The if-statement starts with the keyword if and is followed by the logical
condition a<5 and a colon :. The logical condition a<5 will return either True or False depending on the
value of a. Since a=2, the logical condition a<5 evaluates as True. The line print('less than five')
is indented after the if-statement. The line of code including the print() statement will run if the if-
statement is True. Since the if-statement is True, the indented line print('less than five') runs.
As a result of running these three lines of code, the user sees the text less than five.
Multiple if statements
If-statements can be chained together one after another to create a programmatic flow. For example,
the following code block utilizes three different if-statements, each if-statement is followed by an
indented code block.
In [2]:
a=2
if a<0:
print('is negative')
if a == 0:
print('is zero')
if a>0:
print('is positive')
6|P age
Lab13| Dr. Muhammad Umar
Javed
is positive
Note how each if-statement is followed by a logical condition and a colon :. Also, note how the code
below each if-statement is indented. If the code is left-justified (not indented), all three code lines run,
and the output is different. The code block below will not run unless at least one line of code is
indented after the if-statement. Python's pass keyword is a line of code that does nothing
when executed. pass is added under the if-statments so the code runs error-free.
In [3]:
a=2
if a<0:
pass
print('a is negative')
if a == 0:
pass
print('a is zero')
if a>0:
pass
print('a is positive')
a is negative
a is zero
a is positive
If Else Statements
In Python, if-statements can include else clauses. An else clause is a section of code that runs if the
if-statement is False. If the if-statement is True, the code section under the else clause does not
run.
The general form of an if-statement with an else statement is below:
if <logical_condition>:
<code block 1>
else:
<code block 2>
The keyword else needs to be on its own line and be at the same indentation level as the if keyword that
the else corresponds to. The keyword else needs to be followed by a colon :. Any code that is included
as part of the else statement must be indented the same amount.
A sample if/else code section is below:
In [1]:
7|P age
Lab13| Dr. Muhammad Umar
Javed
a=5
if a>10:
print('a is greater than 10')
else:
print('a is less than 10')
a is less than 10
Since a=5 assigns a value to a that is less than 10, a>10 is False and the code under the if statement does
not run. Therefore, the code under the else statement does run, and "a is less than 10" is printed.
If the value of a is modified so that a is greater than 10, a>10 returns True, and the code under the if
statement will run, and the code under the else keyword will not. In [2]:
a = 20
if a>10:
print('a is greater than 10')
else:
print('a is less than 10')
a is greater than 10
elif
The else if statement can be added to an if statement to run different sections of code depending on
which one of many conditions are True. The basic syntax of an else if section of code is:
if <logical_condition>:
<code block 1>
elif <logical_condition>:
<code block 2>
else:
<code block 3>
The keyword elif must be followed by a logical condition that evaluates as True or False followed by a
colon :. The <code block> runs if the elif condition is True and is skipped if the elif condition is False.
An example section of code using if, elif and else is below:
In [3]:
color = 'green'
if color == 'red':
print('The color is red')
elif color == 'green':
print('The color is green')
8|P age
Lab13| Dr. Muhammad Umar
Javed
else:
print('The color is not red or green')
The color is green
If we modify the code and set color = 'orange', the code under the if does not run, and the code under
the elif does not run either. Only the code under the else is executed.
In [4]:
color = 'orange'
if color == 'red':
print('The color is red')
elif color == 'green':
print('The color is green')
else:
print('The color is not red or green')
The color is not red or green
Try-Except Statements
Try-except statements are another selection structure in Python. Like if, elif and else statements, a try-
except statements select a particular block of code to run based on a condition. Unlike if, elif and else
clauses, try-except blocks are not based on logical conditions. Try-except blocks are based
upon whether a line or section of code returns an error.
Therefore, before we learn how to use try-except statements, we need to understand two types
of errors in Python: syntax errors and exception errors.
Syntax Errors
A syntax error is a type of error in Python that occur when the syntax in a line of code is not valid
Python code. Syntax errors include quotes that are not closed and variable names that do not start with a
letter.
The line of code below contains a syntax error. The string "problem solving is missing a quotation
mark ".
In [1]:
string = "problem solving
File "<ipython-input-1-4c037f6284bc>", line 1
string = "problem solving
^
SyntaxError: EOL while scanning string literal
9|P age
Lab13| Dr. Muhammad Umar
Javed
When you encounter syntax errors in Python, the Python interpreter displays
SyntaxError and often a cryptic message.
Even if a line of code does not run when a program is executed, syntax errors in Python are not
allowed. For instance, a line of code indented after the if statement if 'a' == 'b': will not be executed.
But if the indented line of code contains a syntax error, the Python interpreter still flags the error as a
syntax error and does not complete the program.
In [2]:
if 'a' == 'b':
string = 10problems
File "<ipython-input-2-532ae1edb2a2>", line 2
string = 10problems
^
SyntaxError: invalid syntax
Exception Errors
Syntax errors are lines of code that are not valid Python. Another type of error in Python is an exception
error. Exception errors result when a valid line of Python code cannot run. Lines of code with exception
errors contain valid Python code, but the line of code still cannot be executed.
For example, the statement f = open('file.txt','r') is valid Python code. But if the file file.txt does not
exist, Python throws an exception error because f = open('file.txt','r') cannot be executed.
In [3]:
f = open('file.txt','r')
--------------------------------------------------------------------------- FileNotFoundError Traceback (most
recent call last) <ipython-input-3-cc3c27f5a0c3> in <module>
----> 1 f = open('file.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'
Another valid line of Python code is print(a[0]), but if a is defined as an integer, a can not
be indexed and an exception error is shown.
In [4]:
a=1
print(a[5])
--------------------------------------------------------------------------- TypeError Traceback (most recent call
last) <ipython-input-4-0e1fa8aeb4c3> in <module>
1a=1
----> 2 print(a[5])
10 | P a g e
Lab13| Dr. Muhammad Umar
Javed
TypeError: 'int' object is not subscriptable
Try except statements can be used to try to run sections of Python code that may return an exception
error. The general syntax of a try except statement is below:
try:
<code to try>
except:
<code to run instead>
For instance, if the file file.txt does not exist, a line of code that tries to open file.txt can
be included in a try statement.
In [5]:
try:
f=open('file.txt','r')
except:
print('file does not exist')
file does not exist
Similarly, we can wrap the code a = 5 and print(a[0]) in a try block and attempt to run it. If the line a =
5 and print(a[0]) throws an exception error, the code below except runs.
In [6]:
try:
a=5
print(a[0])
except:
print('variable a is not a list')
variable a is not a list
When the Python code in a try block does run and does not throw an exception error, the code in
the except block does not run.
In [7]:
try:
a = 'Solution'
print(a[0])
except:
print('variable a is not a list')
S
11 | P a g e
Lab13| Dr. Muhammad Umar
Javed
Flowcharts
Flowcharts graphically represent the flow of a program. There are four basic shapes used in a flow chart.
Each shape has a specific use:
• oval: start / end
• parallelogram: input / output
• rectangle: calculations
• diamond: selection structures
Arrows connect the basic shapes in a flowchart. The shapes and arrows of a flowchart
describe the flow of a program from start to end. Flowcharts typically flow from the top
to the bottom or flow from the left to the right. Below is the description of a simple
program: The program starts. Then the program prints out "Output!". Finally, the
program ends. A flowchart that describes this simple program is shown.
12 | P a g e
Lab13| Dr. Muhammad Umar
Javed
A description of a program that includes a calculation is below: The program starts. Next, the program
asks a user for a number. Two is added to the number. Next, the resulting sum is printed. Finally, the
program ends. A flowchart that describes this program is is shown.
13 | P a g e
Lab13| Dr. Muhammad Umar
Javed
The description of another program is below:
The program starts. Next the program asks a user for a number. If the number is greater than zero,
the program prints "Greater than 0", then the program ends. A flow chart that describes this program
is shown.
14 | P a g e
Lab13| Dr. Muhammad Umar
Javed
15 | P a g e
Lab13| Dr. Muhammad Umar
Javed
Selection structures in Python include if, elif, else, try and except. These selection structures allow
certain blocks of code to run or not run based on logical conditions. Logical conditions are
expressions or variables that can be evaluated as True or False. You learned to indent code segments
after if, elif, and else statements. Standard indentation in Python is four spaces. The difference
between syntax errors and exception errors was demonstrated in this chapter. try/except blocks only
check for exception errors.
At the end of the chapter, you learned how to use flowcharts to describe the flow of a program with
four basic shapes and arrows.
Key Terms and Concepts
selection structures
if
logical condition
True
False
programmatic flow
indentation
pass
else
else if
elif
exceptions
syntax
syntax error
valid code
exception error try
except
flow chart
16 | P a g e
Lab13| Dr. Muhammad Umar
Javed
Repetition structures allow the same piece of code to run multiple times. Two repletion structures in Python
are for loops and while loops. For loops run a set number of times. While loops run as long as a specific
logical condition is true.
By the end of this chapter you will be able to:
• use a while loop
• use a for loop
• use the break statement
• use the continue statement
• construct flowcharts that describe programs with loops
For Loops
For Loops are a component of many programming languages. A for loop is a repetition structure where a
section of code runs a specified number of times.
Say we want to print out the statements:
Problem solving in teams
Problem solving in teams
Problem solving in teams
One way to accomplish this task is by coding three print statements in a row:
In [1]:
print('Problem solving in teams')
print('Problem solving in teams')
print('Problem solving in teams')
Problem solving in teams
Problem solving in teams
Problem solving in teams
Another way to accomplish the same task is to use a for loop. The basic structure of a for loop in Python
is below:
for <var> in range(<num>):
<code>
Where <var> can be any variable, range(<num>) is the number of times the for loop runs and <code> are
the lines of code that execute each time the for loop runs. Note the for loop starts with the keyword for
and includes a colon :. Both for and the colon : are required. Also, note <code> is indented. Each line of
code that runs as part of the for loop needs to be indented the same number of spaces. Standard
indentation in Python is four spaces.
17 | P a g e
Lab13| Dr. Muhammad Umar
Javed
The example above can be rewritten using a for loop:
In [2]:
for i in range(3):
print('Problem solving in teams')
Problem solving in teams
Problem solving in teams
Problem solving in teams
Python’s range() function
Python’s range() function returns an iterable list of values starting at zero and ending at n-1. For example,
when range(3) is called, the values 0, 1, 2 are returned. 3 is not part of the output, even though the
function input was range(3). We can be confirm the behavior of range() with a for loop:
In [3]:
for i in range(3):
print(i)
012
Remember Python counting starts at 0 and ends at n-1.
Customizing range()
Python's range() function can be customized by supplying up to three arguments. The general
format of the range function is below:
range(start,stop,step)
When range(3) is called, it produces the same output as
range(0,3,1) (start=0,stop=3,step=1).
Remember Python counting starts at 0 and ends at n-1. If only two arguments are supplied, as
in range(0,3), a step=1 is assumed.
The table below includes examples of the Python's range() function and the associated output.
range() function output
range(3) 0, 1, 2
range(0,3) 0, 1, 2
range(0,3,1) 0, 1, 2
range(2,7,2) 2, 4, 6
range(0,-5,-1) 0, -1, -2, -3, -4
range(2,-3,1) (no output)
18 | P a g e
Lab13| Dr. Muhammad Umar
Javed
A code section that uses a for loop and range() with three arguments is below:
In [4]:
for i in range(5,9,1):
print(i)
5678
For loops with lists
For loops can also be run using Python lists. If a list is used, the loop will run as many times as there are
items in the list. The general syntax is:
for <var> in <list>:
<code>
Where <var> is a variable name assigned to the item in the list and <list> is the list object. Remember to
include a colon : after the list. <code> is the programming code that runs for each item in the list.
An example of a list in a for loop is below:
In [5]:
my_list = ['electrical','civil','mechanical']
for item in my_list:
print(item)
electrical
civil
mechanical
The loop ran three times because there are three items in my_list. Each time through the loop,
the variable item is set to one of the items in the list.
• first time through the loop, item='electrical'
• second time through the loop item='civil'
• third time through the loop item='mechanical'.
For loops with strings
For loops can also be run using strings. In Python, strings can be indexed just like lists. A loop
defined by a string runs as many times as there are characters in the string. The general structure
a for loop using a string is:
for <char> in <string>:
<code>
Where <char> is one of the characters in the string <string>. Just like for loops
with range() and for loops with lists, make sure to include a colon : after the list. <code> is the
19 | P a g e
Lab13| Dr. Muhammad Umar
Javed
programming code that runs for each character in the string. <code> needs to be indented
An example of a string in a for loop is below:
In [6]
for letter in "Gabby":
print(f"looping over letters in name: {letter}")
looping over letters in name: G
looping over letters in name: a
looping over letters in name: b
looping over letters in name: b
looping over letters in name: y
While Loops
A while loop is a type of loop that runs as long as a logical condition is True. When the logical condition
becomes False, the loop stops running. The general form of a while loop in Python is below:
while <logical_condition>:
<code>
The keyword while must be included, as well as a <logical_condition> which can be evaluated as True or
False. The <code> after the while statement must be indented. Each line of code runs in the while loop
needs to be indented the same number of spaces. (Many code editors, including Jupyter notebooks, auto-
indent after a while statement) If you add indentation manually, four space spaces is the Python standard.
An example of a while loop is below:
In [1]:
i=0
while i<4:
print(i)
i = i+1
0 1 2 3
The first line i=0 creates the variable I and assigns it the value 0. The next line declares the logical condition
needed to keep the loop running. The statement i<4 is True or False depending on the variable i. Since i=0,
the
statement i<4 is True and the while loop starts to run. The code inside while the loop prints the value of I
then increases I by 1. When i=4, the statement i<4 is False and the while loop ends.
20 | P a g e
Lab13| Dr. Muhammad Umar
Javed
Using a while loop to validate user input
While loops can be used to validate user input. Say you want to insist that a user inputs positive umber.
You can code this into a while loop that keeps repeating ‘Enter a positive number: ‘ until the user enters
valid input.
The code below continues to ask a user for a positive number until a positive number is entered.
In [2]:
num_input = -1
while num_input < 0:
str_input = input('Enter a positive number: ')
num_input = float(str_input)
Enter a positive number: -2
Enter a positive number: 5
In the section of code above, it is important to initialize the variable num_input with a value that
causes the statement num_input < 0 to evaluate as True. num_input = -1 causes the
statement num_input < 0 to evaluate as True. Besides num_input = -1, any other negative
number would have worked.
If the while statement can't be evaluated as True or False, Python throws an error. Therefore, it
is necessary to convert the user's input from a string to a float. The statement '5' < 0 does not
evaluate to True or False, because the string '5' can't be compared to the number 0.
Break and continue are two ways to modify the behavior of for loops and while loops.
Break
In Python, the keyword break causes the program to exit a loop early. break causes the program
to jump out of for loops even if the for loop hasn't run the specified number of times.break causes
the program to jump out of while loops even if the logical condition that defines the loop is still True.
An example using break in a for loop is below.
In [1]:
for I in range(100):
21 | P a g e
Lab13| Dr. Muhammad Umar
Javed
print(i)
if I == 3:
break
print(‘Loop exited’)
0123
Loop exited
When the loop hits i=3, break is encountered and the program exits the loop.
break
print('Loop exited')
type q to exit the loop: no
type q to exit the loop: q
Loop exited
Continue
In Python, the keyword continue causes the program to stop running code in a loop and start
back at the top of the loop. Remember the keyword break cause the program to exit a loop. continue is
similar, but continue causes the program to stop the current iteration of the loop and start the next iteration
at the top of the loop. A code section that uses continue in a for loop is below.
In [3]:
for i in range(4):
if i==2:
continue
print(i)
013
When the code section is run, the number 2 is not printed. This is because when i=2 the program hits the
continue statement. Therefore, the line print(i) isn't run when i=2. Then the program starts back up at the
start of the loop with the next number i=3.
Summary
Repetition structures allow the same piece of code to run multiple times. For loops run a block of
code a definite number of times. You learned how to use Python's range() function in a for loops
22 | P a g e
Lab13| Dr. Muhammad Umar
Javed
and how to use a list or string in a for loop. A while loop runs a block of code as long as a logical
condition is true. The keywords break and continue causing for and while loops to exit early.
Tasks:
# output
# 10 9 8 7 6 5 4 3 2 1
# output
# 0 7 14 21 28 35 42 49
3. Write a program that appends the square of each number to a new list.
#Appending square to a new list
x = [2,3,4,5,6,7,8]
z = []
for i in range(len(x)):
z.append(x[i]**2)
print("Result: ",z)
23 | P a g e