0% found this document useful (0 votes)
21 views102 pages

CF - Chapter-009

Uploaded by

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

CF - Chapter-009

Uploaded by

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

Chapter No 9 : Loops

C E – 119
Computing Fundamentals (CF)

Compiled By:

Sir Syed University of Engineering & Technology


Engr.Syed Atir Iftikhar
Computer Engineering Department satir@ssuet.edu.pk
University Road, Karachi-75300, PAKISTAN 1
CE - 119 : Computing Fundamentals (CF)
 Course Objectives:
 This course covers the concepts and fundamentals
of computing and programming. Topics includes
history, components of computers, hardware,
software, operating systems, database, networks,
number systems and logic gates. Also it includes
programming topics such as basic building blocks,
loop, decision making statements.

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.

Applying and Implementing problem solving skills and


3 C3
solve problems incorporating the concept of programming.
3
Books

 Text Books
1. Computing Essentials, Timothy O’Leary and Linda O’Leary

2. Introduction to Computers, Peter Norton, 6th Edition, McGraw-Hill

3. Introduction to Programming using Python, Daniel Liang

 Reference Books:
1. Discovering Computers, Misty Vermaat and Susan Sebok,
Cengage Learning

2. Using Information Technology: A Practical Introduction to Computers


& Communications, Williams Sawyer, 9th Edition, McGraw-Hill

3. Introduction to Python, Paul Deitel, Harvey Deitel


4
Marks Distribution

 Total Marks ( Theory ) ___________ 100


 Mid Term ___________ 30
 Assignments + Quizzes + Presentation ___________ 20
 Semester Final Examination Paper ___________ 50

 Total Marks ( Laboratory ) ___________ 50


 Lab File ___________ 15
 Subject Project ___________ 15
 Lab Exam/Quiz ( Theory Teacher ) ___________ 20

 https://sites.google.com/view/muzammil 2050

5
Course Instructors

 Muzammil Ahmad Khan muzammil.ssuet@yahoo.com


Assistant Professor, CED
Room No: BS-04

 Atir Iftikhar satir@ssuet.edu.pk


Lecturer, CED
Room No: BT-05

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

Suppose that you need to print a string


(e.g., "Programming is fun!") a hundred times.

It would be tedious to have to write the following


statement a hundred times:

print("Programming is fun!");

So, how do you solve this problem?

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.

 Python provides a powerful construct called a loop,


which controls how many times in succession an operation
(or a sequence of operations) is performed.

 By using a loop statement, you don’t have to code the print


statement a hundred times; you simply tell the computer to
display a string that number of times.

11
Loop
 Python provides two types of loop statements:
1. while loops and
2. for loops.

 The while loop is a condition-controlled loop;


it is controlled by a true/false condition.

 The for loop is a count-controlled loop


that repeats a specified number of times.
12
Introducing while Loops
 A while loop executes statements repeatedly as long as a
condition remains true.
 The syntax for the while loop is:
while loop-continuation-condition:
# Loop body
Statement(s)

13
Introducing while Loops

The loop that displays Programming is fun! 100 times


is an example of a while loop.
14
Introducing while Loops
 The variable count is initially 0. The loop checks whether
count < 100 is true.
 If so, it executes the loop body—the part of the loop that
contains the statements to be repeated—to display the
message Programming is fun! and increments count by 1.
 It repeatedly executes the loop body until count < 100
becomes false (i.e., when count reaches 100). At this point the
loop terminates and the next statement after the loop
statement is executed.
15
while Loop Flow Chart
while loop-continuation-condition: count = 0
# Loop body while count < 100:
Statement(s)
print("Programming is fun!")
count = count + 1

16
animation

Trace while Loop

Initialize count
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1

17
animation

Trace while Loop

(count < 2) is true


count = 0
while count < 2:
print("Programming is fun!")
count = count + 1

18
animation

Trace while Loop


Print Welcome to Python

count = 0
while count < 2:
print("Programming is fun!")
count = count + 1

19
animation

Trace while Loop

Increase count by 1
count is 1 now
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1

20
animation

Trace while Loop

(count < 2) is still true


since count is 1
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1

21
animation

Trace while Loop

Print Welcome to Python

count = 0
while count < 2:
print("Programming is fun!")
count = count + 1

22
animation

Trace while Loop

Increase count by 1
count = 0 count is 2 now
while count < 2:
print("Programming is fun!")
count = count + 1

23
animation

Trace while Loop

(count < 2) is false since


count is 2 now

count = 0
while count < 2:
print("Programming is fun!")
count = count + 1

24
animation

Trace while Loop

The loop exits. Execute the


next statement after the loop.

count = 0
while count < 2:
print("Programming is fun!")
count = count + 1

25
The while Loop: a Condition-Controlled Loop

 In order for a loop to stop executing, something has


to happen inside the loop to make the condition
false
 Iteration: one execution of the body of a loop
 while loop is known as a pretest loop
 Tests condition before performing an iteration
 Will never execute if condition is false to start with
 Requires performing some steps prior to the loop
Infinite Loops
 Loops must contain within
# Example 1
themselves a way to terminate
i=1
 Something inside a while loop while i>0:
must eventually make the print(i)
condition false i=i+1
 Infinite loop: loop that does not
have a way of stopping # Example 2
 Repeats until program is j=1
interrupted while True:
print(j)
 Occurs when programmer forgets
j=j+1
to include stopping code in the
loop
Loops
 Here is another example illustrating how a loop works:
sum = 0
i=1
while i < 10:
sum = sum + i
i=i+1
print("sum is", sum) # sum is 45
If i < 10 is true, the program adds i to sum. The variable i is
initially set to 1, then incremented to 2, 3, and so on, up to 10.
When i is 10, i < 10 is false, and the loop exits.
So sum is 1 + 2 + 3 + ... + 9 = 45.
Infinite Loops
 Here is another example illustrating about infinite loop works:
sum = 0
i=1
while i < 10:
sum = sum + i
i=i+1
print("sum is", sum) # Infinite Loop
Note that the entire loop body must be indented inside the loop.
Here the statement i = i + 1 is not in the loop body. This loop is
infinite, because i is always 1 and i < 10 will always be true
Problem: An Advanced Math Learning Tool

The Math subtraction learning tool program generates


just one question for each run. You can use a loop to
generate questions repeatedly.

This example gives a program that generates five


questions and reports the number of the correct answers
after a student answers all five questions.

30
Program 5.1
import random

# 1. Generate two random single-digit integers

number1 = random.randint(0, 9)

number2 = random.randint(0, 9)

# 2. If number1 < number2, swap number1 with number2

if number1 < number2:

number1, number2 = number2, number1

31
Program 5.1
# 3. Prompt the student to answer What is number1 - number2?

answer = eval(input("What is " + str(number1) + " - "

+ str(number2) + "? "))

# 5. Repeatedly ask the user the question until it is correct

while number1 - number2 != answer:

answer = eval(input("Wrong answer. Try again. What is "

+ str(number1) + " - " + str(number2) + "? "))

print("You got it!")

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.

 To minimize the number of guesses, enter 50 first.

 If your guess is too high, the magic number is between


0 and 49. If your guess is too low, the magic number is
between 51 and 100.

 So, after one guess, you can eliminate half the numbers from
further consideration.

35
Program 5.2 GuessNumberOneTime.py

import random

# Generate a random number to be guessed

number = random.randint(1, 100)

print("Guess a magic number between 0 and 100")

# Prompt the user to guess the number

guess = eval(input("Enter your guess: "))

36
Program 5.2 GuessNumberOneTime.py

if guess == number:

print("Yes, the number is " + str(number))

elif guess > number:

print("Your guess is too high")

else:

print("Your guess is too low")

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

# Generate a random number to be guessed

number = random.randint(1, 100)

print("Guess a magic number between 0 and 100")

guess = -1

39
Program 5.3 GuessNumber.py

while guess != number:

# Prompt the user to guess the number

guess = eval(input("Enter your guess: "))

if guess == number:

print("Yes, the number is", number)

elif guess > number:

print("Your guess is too high")

else:

print("Your guess is too low")

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.

 Must be distinctive enough so as not to be mistaken


for a regular value in the sequence

 Write a program that reads and calculates the sum of


an unspecified number of integers. The input 0
signifies the end of the input.
SentinelValue Run
42
Ending a Loop with a Sentinel Value
 A common technique for controlling a loop is to designate a
special input value, known as a sentinel value,
which signifies the end of the input. A loop that uses a
sentinel value in this way is called a sentinel-controlled loop.

 The program reads and calculates the sum of an unspecified


number of integers. The input 0 signifies the end of the input.
You don’t need to use a new variable for each input value.
Instead, use a variable named data to store the input value and
use a variable named sum to store the total. Whenever a value
is read, assign it to data and add it to sum if it is not zero.
43
Program 5.4 SentinelValue.py

data = eval(input("Enter an integer (the input exits " +

"if the input is 0): "))

# Keep reading data until the input is 0

sum = 0

while data != 0:

sum += data

data = eval(input("Enter an integer (the input exits " +

"if the input is 0): "))

print("The sum is", sum)

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

 Count-Controlled loop: iterates a specific number of


times
 Use a for statement to write count-controlled loop
 Designed to work with sequence of data items
 Iterates once for each item in the sequence
 General format:
for variable in [val1, val2, etc]:
statements
 Target variable: the variable which is the target of
the assignment at the beginning of each iteration
For Loop with a List

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

i = initialValue # Initialize loop-control variable


while i < endValue:
# Loop body
...
i++ # Adjust loop-control variable
51
Two arguments: starting value and
ending limit :
range(initialValue, endValue)
>>> for v in range(4, 8):
... print(v)
...
4
5
6
7
>>>

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(" Multiplication Table")

# Display the number title

print(" |", end = '')

for j in range(1, 10):

print(" ", j, end = '')

print() # Jump to the new line

print("-----------------------------------------")

58
Program 5.5 MultiplicationTable.py

# Display table body

for i in range(1, 10):

print(i, "|", end = '')

for j in range(1, 10):

# Display the product and align properly

print(format(i * j, '4d'), end = '')

print()# Jump to the new line

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

In mathematics, the greatest common divisor (GCD) of two or


more integers, which are not all zero, is the largest positive
integer that divides each of the integers.
For two integers x, y, the greatest common divisor of x and y is
denoted gcd(x,y). For example, the GCD of 8 and 12 is 4, that
is, gcd(8,12)=4
62
Program 5.6 GreatestCommonDivisor.py

#Prompt the user to enter two integers

n1 = eval(input("Enter first integer: "))

n2 = eval(input("Enter second integer: "))

gcd = 1

k=2

while k <= n1 and k <= n2:

if n1 % k == 0 and n2 % k == 0:

gcd = k

k += 1

print("The greatest common divisor for",

n1, "and", n2, "is", gcd)


63
Program 5.6 GreatestCommonDivisor.py

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:

Suppose that the tuition for a university is $10,000


this year and tuition increases 7% every year.
In how many years will the tuition be doubled?

65
Problem: Predicating the Future Tuition

Before you attempt to write a program, first consider


how to solve this problem by hand. The tuition for the
second year is the tuition for the first year * 1.07.
The tuition for a future year is the tuition of its
preceding year * 1.07.

66
Problem: Predicating the Future Tuition

67
Program 5.6 Tuition.py

year = 0 # Year 0
tuition = 10000 # Year 1

while tuition < 20000:


year += 1
tuition = tuition * 1.07

print("Tuition will be doubled in", year, "years")


print("Tuition will be $" + format(tuition, ".2f"), "in", year, "years")

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.

The probability that the point falls in the circle is circleArea /


squareArea = π / 4.

Write a program that randomly generates 1000000 points that fall


in the square and let numberOfHits denote the number of points
that fall in the circle. So, numberOfHits is approximately 1000000
* (π / 4). can be approximated as 4 * numberOfHits / 1000000.
71
Program 5.7 MonteCarloSimulation.py

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

 The break statement terminates the loop containing it.


Control of the program flows to the statement immediately
after the body of the loop.

 If break statement is inside a nested loop


(loop inside another loop), break will terminate the
innermost loop.

 The break and continue keywords provide additional


controls to a loop.

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

 The continue statement is used to skip the rest of the


code inside a loop for the current iteration only.
 Loop does not terminate but continues on with the next
iteration.

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

while number < 20:


number += 1
sum += number
if sum >= 100:
Break out of break
the loop
print("The number is ", number)
print("The sum is ", sum)

The program adds integers from 1 to 20 in this


order to sum until sum is greater than or equal
to 100. Without break, this program would
The number is 14 calculate the sum of the numbers from 1 to 20.
But with break, the loop terminates when sum
The sum is 105 becomes greater than or equal to 100. Without
break, the output would be:
79
break
 The program adds integers from 1 to 20 in this order to
sum until sum is greater than or equal to 100.
 Without break, this program would calculate the sum of the
numbers from 1 to 20. But with break, the loop terminates
when sum becomes greater than or equal to 100.
 Without break, the output would be:

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

while (number < 20):


number += 1
Jump to the if (number == 10 or number == 11):
end of the continue
iteration sum += number

print("The sum is ", sum)

The sum is 189

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:

The sum is 210

83
Guessing Number Problem Revisited

Here is a program for guessing a number.


You can rewrite it using a break statement.

84
Program 5.8 GuessNumberUsingBreak.py

import random

#Generate a random number to be guessed

number = random.randint(0, 100)

print("Guess a magic number between 0 and 100")

85
Program 5.8 GuessNumberUsingBreak.py

while True:

#Prompt the user to guess the number

guess = eval(input("Enter your guess: "))

if guess == number:

print("Yes, the number is " + str(number))

break

elif guess > number:

print("Your guess is too high")

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

NUMBER_OF_PRIMES = 50 # Number of primes to display

NUMBER_OF_PRIMES_PER_LINE = 10 # Display 10 per line

count = 0 # Count the number of prime numbers

number = 2 # A number to be tested for primeness

print("The first 50 prime numbers are")

89
Program 5.9 PrimeNumbers.py

# Repeatedly find prime numbers

while count < NUMBER_OF_PRIMES:

# Assume the number is prime

isPrime = True #Is the current number prime?

# Test if number is prime

divisor = 2

90
Program 5.9 PrimeNumbers.py

while divisor <= number / 2:

if number % divisor == 0:

# If true, the number is not prime

isPrime = False # Set isPrime to false

break # Exit the for loop

divisor += 1

91
Program 5.9 PrimeNumbers.py

# Display the prime number and increase the count

if isPrime:

count += 1 # Increase the count

print(format(number, '5d'), end = '')

if count % NUMBER_OF_PRIMES_PER_LINE == 0:

# Display the number and advance to the new line

print() # Jump to the new line

# Check if the next number is prime

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

from random import randint

turtle.speed(1) # Set turtle speed to slowest

# Draw 16 by 16 lattices

turtle.color("gray") # Color for lattice

x = -80

95
Program 5.10 RandomWalk.py

for y in range(-80, 80 + 1, 10):

turtle.penup()

turtle.goto(x, y) # Draw a horizontal line

turtle.pendown()

turtle.forward(160)

96
Program 5.10 RandomWalk.py

y = 80

turtle.right(90)

for x in range(-80, 80 + 1, 10):

turtle.penup()

turtle.goto(x, y) # Draw a vertical line

turtle.pendown()

turtle.forward(160)

97
Program 5.10 RandomWalk.py

turtle.pensize(3)

turtle.color("red")

turtle.penup()

turtle.goto(0, 0) # Go to the center

turtle.pendown()

x = y = 0 # Current pen location at the center of lattice

while abs(x) < 80 and abs(y) < 80:

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy