CIT 101 Py Lesson 9 Final
CIT 101 Py Lesson 9 Final
CIT 101 Py Lesson 9 Final
This lesson serves as a supplementary material for Practical 7 & Future Practicals.
S
Sttrruuccttuurreedd A
Apppprrooaacchh ttoo P
Prrooggrraam
mmmiinngg
Repetition
When we do something again and again we say it is being repeated. To
repeat something we have to come to its original state and we say we have
completed a cycle. So repeating is completing a task in a cyclic manner.
The earth completes cycles around the sun making days, weeks, years etc.
We do much repetitive work every day. Sleeping & awakening, inhaling &
exhaling are to examples of repetitive work we do.
1. Infinite repetition – Nonstop (Earth moves around the Sun) – Figure 1-1 shows the logic
2. Finite repetition – Repeat some task, a known number of times. – Figure 2 shows the logic
START START
.
counter := 1
Do Something
Loop
Figure 1-1: Infinite Repetition ? counter False
<= 10
Finite Repetition is characterized by:
TEST
True END
An initial value. (e.g. counter := 1) Output
counter value
End value. (e.g. counter:= 10)
Increase
Incremental value (e.g. 1) counter by 1
1. ‘for’ loop
2. ‘while’ loop
Page 1 of 10
‘for’ Loops
start - Any integer which demarks the start value (Optional). Default is 0
stop - An integer which demarks the end value (Mandatory).
step - An integer specifying an increment (Optional). Default is 1
Examples:
-3 -2 -1 0 1 2 3
1x2x3x4x
‘for’ loop is used to iterate over an Iterator. (a list, a tuple, a dictionary, a set, or a string)
10 11 12 13
ab
cd
ef
Page 2 of 10
Iterating over a string
>>> s = "abcde" # ‘s’ is a list
>>> for i in s: # Display all characters in ‘s’
... print(i, end = ‘ ‘)
abcde
abc 123
pqr 345
OUTPUT:
2 4 6 8 10 12 14 16 18 20
OUTPUT:
3 9 15 21 27 33 39 45
# Find the numbers that end with digit 3 in a given list - Saved as for3.py
list = [13,15,24,26,43,73,21,40,63]
for num in list:
if num % 10 == 3:
print(num, end = ' ')
OUTPUT:
13 43 73 63
# Display the two digit numbers whose sum of the digits is 7 - Saved as for4.py
OUTPUT:
16 25 34 43 52 61 70
Page 3 of 10
# Program to create a list containing odd numbers between 1 and 31
# - Saved as for5.py
list=[]
for i in range(1,31,2):
list.append(i)
print(list)
OUTPUT:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
celsius = [-40.0,-30.0, -20.0, -10.0, 0.0, 10.0, 20.0, 30.0, 40.0, 50.0]
fahrenheit = []
for i in celsius:
fah = i*9/5 + 32
fahrenheit.append(fah)
OUTPUT:
7 Times Table
=============
1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35
6 x 7 = 42
7 x 7 = 49
8 x 7 = 56
9 x 7 = 63
10 x 7 = 70
11 x 7 = 77
12 x 7 = 84
Page 4 of 10
Random Numbers in Computing
Random numbers are an important part of computing. Cryptography, Simulation, Statistics, Monte Carlo
computations, games and system testing all rely on random number generation.
.
Important Uses of Random Numbers include program testing, games, simulations etc.
Real-random Numbers - uses a physical source of randomness. In a sequence, if knowing the first n
th
numbers, we are not able to predict the (n+1) term with 100% accuracy.
Pseudo-random Numbers
The unpredictability of random numbers however, leads to big problems when you attempt to use a
computer to generate random sequences. Computers are deterministic, meaning that their behavior is at
any time is completely predictable based upon its prior behavior. So, computer generated random numbers
are considered pseudo-random numbers. A pseudo-random number or sequence “appears” to be random,
but in reality is not.
The random module is a built-in module in standard library which is to generate pseudo-random numbers
.
Generate Random Floats
>>> random.randrange(1, 10) # Returns a randomly selected element from the range 1 to 10
2
The random.choice() method returns a randomly selected element from a non-empty sequence. An empty
sequence as argument raises an IndexError.
Page 5 of 10
>>> random.choice([16,3,65,17,22,35])
17
>>> random.choice((35,13,54,39,21,85))
13
s = [16,3,65,17,22,35]
>>> random.shuffle(s)
>>> s
[22, 65, 3, 35, 16, 17]
# The Program counts the number of times that a prime number is generated
# when a die is thrown 5 times - Saved as for8.py
import random
count = 0
for i in range(1,6):
outcome = random.randint(1,7)
if outcome == 2 or outcome == 3 or outcome == 5:
count += 1
print(f"Number of occurrences of a prime number = {count}")
OUTPUT:
False
‘while’ is a keyword in Python Evaluate
Condition
The while loop in Python is used to execute a single
TEST
True
statement of a block of statements repeatedly as long
as a given condition is True. Statement Block
while condition:
statements
‘while’ loop executes as far as the given condition is true. Therefore in situations where the condition is
constantly true the while loop executes forever. This situation is known as infinite looping.
Page 6 of 10
Examples:
‘break’ Statement
‘break’ statement allows you to terminate the execution of a loop conditionally.
count = 1
while True:
print(f'I have given up all my bad habits- {count}')
count +=1
if count == 5:
break # After 4 loops counter value become 5 and loop will be terminated.
print('End of looping')
Output:
‘continue’ Statement
‘continue’ statement allows you to executing statements below that conditionally and execution will be handed
over to the while loop to continue.
# This program demonstrates the use of ‘continue’ and ‘break’ in loops - Saved as whileinf2.py
Output:
Tic - 4
Tic - 5
End of looping
Page 7 of 10
Finite Loops with ‘while’
Example 1:
while i <= 5:
print(f"Loop{i}") # Display current loop
i += 1 # For each loop Increase i by 1 until i becomes 5
Output:
Loop1
Loop2
Loop3
Loop4
Loop5
Example 2:
import sys
if n <= 0:
print("Wrong entry! Quitting ...")
sys.exit()
sum = 0 # Initialize a variable to store 'sum'
i = 1 # Set loop control variable to 1
while i <= n:
sum += i
i += 1 # update loop control variable by 1 for each iteration
Page 8 of 10
OUTPUT (Fuurth run):
Nested Loops
Example 1:
OUTPUT:
1 1
1 2
1 3
2 1
2 2
2 3
Example 2:
for i in person:
for j in money:
print(i, 'have', j, end = '')
OUTPUT:
Special Applications
# GCE(O/L) Graphs
# Plot the graph of 2x2 – 3x +2 in the range -5 <= x < 8 – Saved as gr1.py
Page 9 of 10
Armstrong Numbers
th
An n-digit number that is the sum of the n powers of its digits is called an n-narcissistic (නාසිසිස්ටික් -
நாசீசிஸ்டிக்) number also called an Armstrong Number.
.
3 3 3
E.g. 1 + 5 + 3 = 153
115132219018763992565095597973971522400, 115132219018763992565095597973971522401
000
001
153
370
371
407
Page 10 of 10