CF - Chapter-009
CF - Chapter-009
C E – 119
Computing Fundamentals (CF)
Compiled By:
2
CE - 119 : Computing Fundamentals (CF)
Course Learning Outcomes ( CLO )
CLO Level
Outcome Statement
No. *
Explain the fundamental knowledge and concepts about
1 computing infrastructure including hardware, software, C2
database and networks.
Applying and Implementing number systems and logic
2 C3
gates.
Text Books
1. Computing Essentials, Timothy O’Leary and Linda O’Leary
Reference Books:
1. Discovering Computers, Misty Vermaat and Susan Sebok,
Cengage Learning
https://sites.google.com/view/muzammil 2050
5
Course Instructors
6
CE – 119: Computing Fundamentals Chapter
Loops
Compiled By:
Engr.Syed Atir Iftikhar satir@ssuet.edu.pk
7
Objectives
To write programs for executing statements repeatedly by
using a while loop
To develop loops following the loop design strategy
To control a loop with the user’s confirmation
To control a loop with a sentinel value
To obtain a large amount of input from a file by using input
redirection instead of typing from the keyboard
To use for loops to implement counter-controlled loops
To write nested loops
To learn the techniques for minimizing numerical errors
To learn loops from a variety of examples (GCD,
FutureTuition, MonteCarloSimulation, PrimeNumber)
To implement program control with break and continue
To use a loop to control and simulate a random walk 8
Motivations
print("Programming is fun!");
9
Opening Problem
Problem:
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
100
times …
…
…
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
10
Loop
A loop can be used to tell a program to execute statements
repeatedly.
11
Loop
Python provides two types of loop statements:
1. while loops and
2. for loops.
13
Introducing while Loops
16
animation
Initialize count
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
17
animation
18
animation
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
19
animation
Increase count by 1
count is 1 now
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
20
animation
21
animation
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
22
animation
Increase count by 1
count = 0 count is 2 now
while count < 2:
print("Programming is fun!")
count = count + 1
23
animation
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
24
animation
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
25
The while Loop: a Condition-Controlled Loop
30
Program 5.1
import random
number1 = random.randint(0, 9)
number2 = random.randint(0, 9)
31
Program 5.1
# 3. Prompt the student to answer What is number1 - number2?
32
Program 5.1
Output:
What is 9 - 5? 1
Wrong answer. Try again. What is 9 - 5? 2
Wrong answer. Try again. What is 9 - 5? 3
Wrong answer. Try again. What is 9 - 5? 4
You got it!
33
Problem: Guessing Numbers
Write a program that randomly generates an integer
between 0 and 100, inclusive. The program prompts the
user to enter a number continuously until the number
matches the randomly generated number.
For each user input, the program tells the user whether
the input is too low or too high, so the user can choose
the next input intelligently. Here is a sample run:
GuessNumberOneTime Run
GuessNumber Run
34
Problem: Guessing Numbers
The magic number is between 0 and 100.
So, after one guess, you can eliminate half the numbers from
further consideration.
35
Program 5.2 GuessNumberOneTime.py
import random
36
Program 5.2 GuessNumberOneTime.py
if guess == number:
else:
37
Program 5.2 GuessNumberOneTime.py
Output:
Guess a magic number between 0 and 100
Enter your guess: 50
Your guess is too low
>>> 70
70
38
Program 5.3 GuessNumber.py
import random
guess = -1
39
Program 5.3 GuessNumber.py
if guess == number:
else:
40
Program 5.3 GuessNumber.py
Output:
Guess a magic number between 0 and 100
Enter your guess: 50
Your guess is too low
Enter your guess: 60
Your guess is too high
Enter your guess: 55
Your guess is too high
Enter your guess: 52
Yes, the number is 52
41
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify
the end of the loop. Such a value is known as a
sentinel value.
sum = 0
while data != 0:
sum += data
44
Program 5.4 SentinelValue.py
Output:
Enter an integer (the input exits if the input is 0): 2
Enter an integer (the input exits if the input is 0): 3
Enter an integer (the input exits if the input is 0): 4
Enter an integer (the input exits if the input is 0): 0
The sum is 9
45
Caution
Don’t use floating-point values for equality checking in a loop
control. Since floating-point values are approximations for some
values, using them could result in imprecise counter values and
inaccurate results. Consider the following code for computing
1 + 0.9 + 0.8 + ... + 0.1:
item = 1
sum = 0
while item != 0: # No guarantee item will be 0
sum += item
item -= 0.1
print(sum)
Variable item starts with 1 and is reduced by 0.1 every time the
loop body is executed. The loop should terminate when item
becomes 0. However, there is no guarantee that item will be
exactly 0, because the floating-point arithmetic is approximated.
This loop seems OK on the surface, but it is actually an infinite
loop. 46
The for Loop: a Count-Controlled Loop
48
Using the range Function with the for
Loop
The range function simplifies the process of
writing a for loop
range returns an iterable object
Iterable: contains a sequence of values that can
be iterated over
Range characteristics:
One argument: used as ending limit
Two arguments: starting value and ending limit
Three arguments: third argument is step value
One argument: used as ending limit:
range(endValue)
>>> for i in range(4):
... print(i)
...
0
1
2
3
>>>
- i starts from 0
50
Two arguments: starting value and
ending limit :
range(initialValue, endValue)
for i in range(initialValue, endValue):
# Loop body
52
Three arguments: third argument is step
value
range(initialValue, endValue, step)
>>> for v in range(3, 9, 2):
... print(v)
...
3
5
7
>>>
53
Generating an Iterable Sequence that
Ranges from Highest to Lowest
The range function can be used to generate a
sequence with numbers in descending order
Make sure starting number is larger than end limit,
and step value is negative
Example: range (5, 1, -1)
Three arguments: third argument is step
value
range(initialValue, endValue, step)
>>> for v in range(5, 1, -1):
... print(v)
...
5
4
3
2
>>>
55
Nested Loops Output:
Nested loop: loop that is contained i= 1 j= 1
i= 1 j= 2
inside another loop i= 1 j= 3
Inner loop goes through all of its i= 2 j= 1
iterations for each iteration of outer i= 2 j= 2
loop i= 2 j= 3
i= 3 j= 1
Inner loops complete their i= 3 j= 2
iterations faster than outer loops i= 3 j= 3
i= 4 j= 1
Total number of iterations in nested i= 4 j= 2
loop: number_iterations_inner x i= 4 j= 3
number_iterations_outer
Number of Iterations
for i in range(1,5): = 4 x 3 = 12
for j in range(1,4):
print("i=",i," j=",j)
56
Nested Loops
Nested loop: loop that is contained inside another
loop
Problem:
Write a program that uses nested for loops to print a
multiplication table.
57
Program 5.5 MultiplicationTable.py
print("-----------------------------------------")
58
Program 5.5 MultiplicationTable.py
59
Program 5.5 MultiplicationTable.py
Output:
Multiplication Table
| 1 2 3 4 5 6 7 8 9
-----------------------------------------
1| 1 2 3 4 5 6 7 8 9
2 | 2 4 6 8 10 12 14 16 18
3 | 3 6 9 12 15 18 21 24 27
4 | 4 8 12 16 20 24 28 32 36
5 | 5 10 15 20 25 30 35 40 45
6 | 6 12 18 24 30 36 42 48 54
7 | 7 14 21 28 35 42 49 56 63
8 | 8 16 24 32 40 48 56 64 72
9 | 9 18 27 36 45 54 63 72 81 60
Problem: Finding the Greatest Common Divisor
Write a program that prompts the user to enter two positive
integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest
common divisor is 2. Suppose you enter two integers 16 and 24,
their greatest common divisor is 8. So, how do you find the
greatest common divisor? Let the two input integers be n1 and
n2. You know number 1 is a common divisor, but it may not be
the greatest commons divisor. So you can check whether k
(for k = 2, 3, 4, and so on) is a common divisor for n1 and n2,
until k is greater than n1 or n2.
61
Problem: Finding the Greatest Common Divisor
gcd = 1
k=2
if n1 % k == 0 and n2 % k == 0:
gcd = k
k += 1
Output:
Enter first integer: 100
Enter second integer: 90
The greatest common divisor for 100 and 90 is 10
64
Problem: Predicating the Future Tuition
Problem:
65
Problem: Predicating the Future Tuition
66
Problem: Predicating the Future Tuition
67
Program 5.6 Tuition.py
year = 0 # Year 0
tuition = 10000 # Year 1
68
Program 5.6 Tuition.py
Output:
Tuition will be doubled in 11 years
Tuition will be $21048.52 in 11 years
69
Problem: Monte Carlo Simulation
The Monte Carlo simulation refers to a technique that uses
random numbers and probability to solve problems. This method
has a wide range of applications in computational mathematics,
physics, chemistry, and finance. This section gives an example of
using the Monto Carlo simulation for estimating .
y
circleArea / squareArea = / 4.
1
x can be approximated as 4 *
-1 1
numberOfHits / 1000000.
-1
MonteCarloSimulation Run
70
Problem: Monte Carlo Simulation
Assume the radius of the circle is 1. So, the circle area is and the
square area is 4. Randomly generate a point in the square.
import random
NUMBER_OF_TRIALS = 100000 # Constant
numberOfHits = 0
for i in range(NUMBER_OF_TRIALS):
x = random.random() * 2 - 1
y = random.random() * 2 - 1
if x * x + y * y <= 1:
numberOfHits += 1
pi = 4 * numberOfHits / NUMBER_OF_TRIALS
print("PI is", pi)
72
Program 5.7 MonteCarloSimulation.py
Output:
PI is 3.14352
73
break Statement in Python
74
break Statement in Python
# Use of break statement
# inside loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
s
t
r
The end
75
Python continue statement
76
Python continue statement
# Program to show the use of
# continue statement inside
# loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
s
t
r
n
g
The end
77
Using break and continue
Examples for using the break and continue keywords:
78
break
sum = 0
number = 0
The number is 20
The sum is 210
80
continue
You can also use the continue keyword in a loop.
When it is encountered, it ends the current iteration and
program control goes to the end of the loop body.
In other words, continue breaks out of an iteration, while
the break keyword breaks out of a loop.
81
continue
sum = 0
number = 0
82
continue
The program adds all the integers from 1 to 20 except
10 and 11 to sum.
The continue statement is executed when number becomes
10 or 11. The continue statement ends the current iteration
so that the rest of the statement in the loop body is not
executed; therefore, number is not added to sum when it is
10 or 11. Without continue, the output would be as follows:
83
Guessing Number Problem Revisited
84
Program 5.8 GuessNumberUsingBreak.py
import random
85
Program 5.8 GuessNumberUsingBreak.py
while True:
if guess == number:
break
else:
print("Your guess is too low")
86
Program 5.8 GuessNumberUsingBreak.py
Output:
Guess a magic number between 0 and 100
Enter your guess: 50
Your guess is too low
Enter your guess: 80
Your guess is too low
Enter your guess: 90
Your guess is too high
Enter your guess: 87
Yes, the number is 87
87
Problem: Displaying Prime Numbers
Write a program that displays the first 50 prime numbers in five
lines, each of which contains 10 numbers. An integer greater
than 1 is prime if its only positive divisor is 1 or itself.
For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9
are not.
Solution:
The problem can be broken into the following tasks:
For number = 2, 3, 4, 5, ..., test whether the number is prime.
Determine whether a given number is prime.
Count the prime numbers.
Print each prime number, and print 10 numbers per line.
88
Program 5.9 PrimeNumbers.py
89
Program 5.9 PrimeNumbers.py
divisor = 2
90
Program 5.9 PrimeNumbers.py
if number % divisor == 0:
divisor += 1
91
Program 5.9 PrimeNumbers.py
if isPrime:
if count % NUMBER_OF_PRIMES_PER_LINE == 0:
number += 1
92
Program 5.9 PrimeNumbers.py
Output:
93
Turtle Graphics
You can use Turtle graphics to simulate a random walk.
Turtle program that simulates a random walk in a lattice
(e.g., like walking around a garden and turning to look at
certain flowers) that starts from the center and ends at a point
on the boundary,
94
Program 5.10 RandomWalk.py
import turtle
# Draw 16 by 16 lattices
x = -80
95
Program 5.10 RandomWalk.py
turtle.penup()
turtle.pendown()
turtle.forward(160)
96
Program 5.10 RandomWalk.py
y = 80
turtle.right(90)
turtle.penup()
turtle.pendown()
turtle.forward(160)
97
Program 5.10 RandomWalk.py
turtle.pensize(3)
turtle.color("red")
turtle.penup()
turtle.pendown()
r = randint(0, 3)
98
Program 5.10 RandomWalk.py
if r == 0:
x += 10 # Walk east
turtle.setheading(0)
turtle.forward(10)
elif r == 1:
y -= 10 # Walk south
turtle.setheading(270)
turtle.forward(10)
99
Program 5.10 RandomWalk.py
elif r == 2:
x -= 10 # Walk west
turtle.setheading(180)
turtle.forward(10)
elif r == 3:
y += 10 # Walk north
turtle.setheading(90)
turtle.forward(10)
turtle.done()
100
Program 5.10 RandomWalk.py
Output:
101
102