CIT 101 Py Lesson 9 Final

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Bachelor of Applied Information Technology

Degree Programme – (DAIT)

CIT101 Programming Fundamentals


Lesson 9

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.

Python facilitates a control structure for repetition. We call it Repetitive


Control Structure.

Repetition is also known as Iteration. Repetition can be divided into two.

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

Our main concern is on finite repetition

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

Figure 2: Finite Repetition – Counting to 10

Python transforms these ideas into code by using two mechanisms.

1. ‘for’ loop

2. ‘while’ loop

Page 1 of 10
‘for’ Loops

 ‘for’ loop is made up of the keyword ‘for’,


 ‘for’ loop uses the operator ‘in’
 ‘for’ loop involves the range() function

range() function and its parameters


range(start, stop, step)

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

Note: range() returns a list iterator (list object)

Examples:

>>> for i in range(1,6): # i is a loop control variable


... print(i)
...
1
2
3
4
5

>>> for i in range(1,5): # i is a loop control variable


... print(i, end = ‘ ‘) # for each i the end character is a space. (Used for joining)
...
1234

for i in range(-3,4): # i is a loop control variable


... print(i, end = ' ') # for each i the end character is a space. (Used for joining)

-3 -2 -1 0 1 2 3

>>> for i in range(1,5): # i is a loop control variable


... print(i, end = 'x') # for each i the end character is a space. (Used for joining)

1x2x3x4x

‘for’ loop is used to iterate over an Iterator. (a list, a tuple, a dictionary, a set, or a string)

Iterating over a list


>>> a = [10,11,12,13] # ‘a’ is a list
>>> for i in a: # Display all elements of ‘a’
... print(i, end = ' ')

10 11 12 13

>>> lst = ["ab","cd","ef"] # ‘lst’ is a list

>>> for i in lst: # Display all elements of ‘lst’


... print(i)

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

Iterating over a dictionary


>>> d = {"Frog":"Toad", "Dog":"Puppy", "Man":"Human"} # ‘d’ is a dictionary
>>> for i in d: # Display all characters in ‘d’
... print(i, end = ' ')

Frog Dog Man

>>> d = dict() # Create an empty is a dictionary


>>> d['abc'] = 123 # Insert key:value pair
>>> d['pqr'] = 345 # Insert key:value pair
>>> for i in d: # Display all elements of ‘d’
... print("%s %d" %(i,d[i]))

abc 123
pqr 345

# Program to generate even numbers between 1 and 21 Saved as for1.py

for index in range(2,21,2): # Start from 2 and go in steps of 2


print(index, end = ' ')

OUTPUT:

2 4 6 8 10 12 14 16 18 20

# Numbers between 1 and 50 which are divisible by 3 # but 4 # - Saved as for2.py

for num in range(1,51,2):


if num % 3 == 0 and num % 4 != 0:
print(num, end = ' ')

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

for num in range(10,100):


if num % 10 + num // 10 == 7:
print(num, end = ' ')

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]

# Program to generate a list of temperatures in Fahrenheit, given that a list #


of temperatures in Celsius is available - Saved as for6.py

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)

print("List of Celsius Temperature \n", celsius )


print()
print("List of Fahrenheit Temperature\n", fahrenheit )

OUTPUT:

List of Celsius Temperature


[-40.0, -30.0, -20.0, -10.0, 0.0, 10.0, 20.0, 30.0, 40.0, 50.0]

List of Fahrenheit Temperature


[-40.0, -22.0, -4.0, 14.0, 32.0, 50.0, 68.0, 86.0, 104.0, 122.0]

# The Program generates an n-times multiplication table - Saved as for7.py

num = int(input("Enter an integer to generate a Multiplication Table:"))


print()
print(f"{num} Times Table")
print('='*13)
for i in range(1,13):
print(f"{i} x { num} = {i*num}")

Enter an integer to generate a Multiplication Table:7

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.

Different Type of Random Numbers

 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 – mimic the properties of real random numbers.

 Quasi-random Numbers – uniformly distributed

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.

Generation of Pseudo Random Numbers in Python


Random Module in Python

The random module is a built-in module in standard library which is to generate pseudo-random numbers
.
Generate Random Floats

>>> import random


>>> random.random() # Returns random float numbers between 0.0 to 1.0.
0.3675892607268494

Generate Random Integers

>>> import random


>>> random.randint(1, 100) # Returns a random integer between 1 & 100 inclusive
63

>>> random.randrange(1, 10) # Returns a randomly selected element from the range 1 to 10
2

>>> random.randrange(1, 10, 2)


5

Select Random Elements

The random.choice() method returns a randomly selected element from a non-empty sequence. An empty
sequence as argument raises an IndexError.

>>> random.choice('Python') # Returns a randomly selected element from a non-empty sequence.


'h’

Page 5 of 10
>>> random.choice([16,3,65,17,22,35])
17

>>> random.choice((35,13,54,39,21,85))
13

Shuffle Elements Randomly

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:

Number of occurrences of a prime number = 2


Number of occurrences of a prime number = 4

Looping with ‘while’

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

 When the condition becomes False, the looping stops


and the program execution is resumed at the next
statement after the block of the while loop.
Figure 2: Logic of the 'while' loop

The syntax of the while loop

while condition:
statements

Infinite Looping with ‘while’

‘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:

while True: while 1==1: while 1:


print(‘Non-stop’) print(‘Non-stop’) print(‘Non-stop’)

while ‘A’ != ‘B’: while not False: while not 1>2:


print(‘Non-stop’) print(‘Non-stop’) print(‘Non-stop’)

‘break’ Statement
‘break’ statement allows you to terminate the execution of a loop conditionally.

# This program demonstrates how to convert an infinite loop to a finite loop


# - Saved as whileinf2

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:

I have given up all my bad habits- 1


I have given up all my bad habits- 2
I have given up all my bad habits- 3
I have given up all my bad habits- 4
End of looping

‘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

count = 0 # Set a counter to 0


while True: # Start an infinite loop
count +=1 # Update the counter by 1
if count <= 3:
continue # As far as counter value is not > 3 check the condition
elif count == 6:
break # Stop when the counter value is 6
else:
print(f'Tic - {count}') # Print ‘Tic’ until counter become 6
print('End of looping')

Output:

Tic - 4
Tic - 5
End of looping

Page 7 of 10
Finite Loops with ‘while’
Example 1:

# Demonstration of while loop - Saved as while1.py


# Program performs 5 loops.

i = 1 # Set loop control variable to 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:

# Adding natural numbers together - Saved as while2.py


# Program calculates the sum of all natural numbers from 1 to n inclusive
# when input a value for n. [1+2+3+4 ... + n]

import sys

n = int(input("Enter the last integer of the series 1..n: "))

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

print(f"1+2+3+ .. + {n} =", sum) # print the sum

OUTPUT (First run):

Enter the last integer of the series 1..n: 0


Wrong entry! Quitting ...

OUTPUT (Second run):

Enter the last integer of the series 1..n: -5


Wrong entry! Quitting ...

OUTPUT (Third run):

Enter the last integer of the series 1..n: 10


1+2+3 .. + 10 = 55

Page 8 of 10
OUTPUT (Fuurth run):

Enter the last integer of the series 1..n: 100


1+2+3+ .. + 100 = 5050

Nested Loops

A nested loop is a loop within a loop.

Example 1:

# Nested for - Saved as nesfor1.py


for i in range(1,3): # Repeat the following loop 2 times
for j in range(1,4): # Repeat the following statement 3 times
print(i,j) # This statement will be executed 2x3 = 6 times

OUTPUT:

1 1
1 2
1 3
2 1
2 2
2 3
Example 2:

# Nested Loops Demonstration - Saved as nesfor2.py


money = ["10 dollars, ", "20 Pounds and ", "30 Euros\n"]
person = ["I", "We"]

for i in person:
for j in money:
print(i, 'have', j, end = '')

OUTPUT:

I have 10 dollars, I have 20 Pounds and I have 30 Euros


We have 10 dollars, We have 20 Pounds and We have 30 Euros

Special Applications
# GCE(O/L) Graphs
# Plot the graph of 2x2 – 3x +2 in the range -5 <= x < 8 – Saved as gr1.py

import matplotlib.pyplot as plt

y_values = [] # Create a y_values list


for x in range(-5, 8): # Calculate y
y = 2*x*x - 3*x + 2
y_values.append(y) # Insert data into the list

plt.plot(y_values) # Plot the values in a graph


plt.ylabel('Y Values') # Set y- axis label
plt.show() # Show the graph

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

4-digit Armstrong Numbers: 1634, 8208, 9474

5-digit Armstrong Numbers: 54748, 92727, 93084

39-digit Armstrong Numbers:

115132219018763992565095597973971522400, 115132219018763992565095597973971522401

# Display 3-digit Armstrong numbers - Saved as nesfor3.py


# The program uses 3 loops
for i in range(0,10):
for j in range(0,10):
for k in range(0,10):
if i*i*i + j*j*j + k*k*k == 100*i + 10*j + k:
sum = 100*i + 10*j + k
if sum == 0:
print('000')
elif sum == 1:
print('001')
else:
print(sum)
OUTPUT:

000
001
153
370
371
407

Page 10 of 10

You might also like