0% found this document useful (0 votes)
4 views32 pages

Computer Programming - Lecture 5

The document discusses the concept of iteration in computer programming, focusing on loops, specifically while and for loops in Python. It explains how to use break and continue statements, the range function, and nested loops, along with examples and common errors associated with loops. Additionally, it includes exercises and questions to reinforce understanding of these concepts.

Uploaded by

Panda
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)
4 views32 pages

Computer Programming - Lecture 5

The document discusses the concept of iteration in computer programming, focusing on loops, specifically while and for loops in Python. It explains how to use break and continue statements, the range function, and nested loops, along with examples and common errors associated with loops. Additionally, it includes exercises and questions to reinforce understanding of these concepts.

Uploaded by

Panda
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/ 32

Computer

Programming: Lecture
5
Outline
• Iteration
Iteration
• Iteration is a fundamental concept in computer programming that
involves repeating a set of instructions multiple times until a certain
condition is met.
Loops
• A loop repeats a sequence of statements
We have two types of loops in python:
• while loop: are used to iterate over a block of code as long as a certain
condition is met.
• for loop: are used to iterate over a sequence of values. This could be a
list, tuple, string, or any other iterable object.
The while loop

while(condition):
<statements>
The while loop
More formally, here is the flow of execution for a while statement:
• Evaluate the condition, yielding True or False.
• If the condition is false, exit the while statement and continue execution at
the next statement.
• If the condition is true, execute the body
Example
Let us count 1 up to 10:

i=1
while(i <= 10):
print(i)
i=i+1

Demo: Let us write a function that can count up to a positive integer passed as an argument
Example
Let us write an accumulator loop:
Demo: Let us add a number 1 to 100
Example
Demo: Let us write a factorial function
Break statement
The break statement is used to exit a loop early. It can be used in both for loops and while loops.

i=0 0
while(i <= 10): 1
if(i == 5): 2
break 3
print(i) 4
i=i+1 The current value of I is: 5
print("The current value of i is:",i)
Example
Guess the output of this code:
i = 11
while(i <= 20):
if(i % 5 == 0):
break
print(i)
i=i+1
print("The current value of i is:",i)
Demo
Let us find the LCM of two numbers:
Continue statement
The continue statement is used to skip the current iteration of a loop and continue with the next
iteration.

while(i < 5):


i += 1 1
if(i == 3): 2
4
continue 5
print(i)
Continue Example

i=0 1
while(i < 10): 3
i=i+1 5
if(i % 2 == 0): 7
continue 9
print(i)
Continue statement
Guess the output of this code:
i=0
while(i < 10):
print(“Hello”)
if(i % 2 == 0):
continue
print(i)
i=i+1
Demo: While loop
Let us write arithmetic quiz game
Common Errors

x = 10
while(x > 0):
x += 1
Common Errors
Off by one error: A logic error that occurs in programming when an
iterative loop iterates one time too many or too few.
Arises when programmer makes mistakes such as
◦ Fails to take account that a sequence starts at zero rather than one
◦ Using “less than or equal to” in place of “less than” …
The range function
The range() function in Python is used to create a sequence of numbers. The syntax for the
range() function is as follows:

range(start, stop, step)

Range creates a sequence of number from the start to stop -1 (+1 if it is in reverse) apart by
the step value
The range function
range(0,10) -> creates a sequence starting 0 and ending at 9
range(0,10,2) -> creates a sequence containing 0,2,4,6, and 8
range(10) -> creates a sequence starting at 0 and ending at 9
range(10,1,-1) -> creates a sequence starting at 10 and ending at 2
For loop
The loop variable picks up the next value in a sequence on each pass through the loop

for variable in sequence:


block of code
For loop example

0
for i in range(5): 1
2
print(i)
3
4
Example
Let us write an accumulator loop:
Demo: Let us add a number 1 to 100
Demo: Let us write a factorial function
Break and Continue
for letter in "python": for letter in "python":
if(letter == "h"): if(letter == "h"):
break continue
print(letter) print(letter)
What is the output of this code?
rows = 5 rows = 5
for i in range(1, rows + 1): for i in range(rows, 0, -1):
print('*' * i) print('*' * i)

Question: Convert this to while loop


What is the output of this code?
rows = 5
for i in range(1, rows + 1):
print(' ' * (rows - i) + '*' * i)

Question: Convert it to while loop


Nested Loops
• A nested loop is a loop that is contained within another loop.
• The inner or outer loop can be any type, such as a while loop or for loop. For example, the outer
for loop can contain a while loop and vice versa.
•Each time the outer loop is repeated, the inner loops are re-entered and started anew.

# outer loop
# outer loop
for element in sequence:
while condition:
# inner loop
# inner loop
for element in sequence:
while condition:
# body of inner loop
# body of inner loop
# body of outer loop
# body of outer loop
Example
What is the output of the following snippets

for i in range(5): i=0


for j in range(2): while(i < 5):
print(i,j) j=0
while(j < 2):
print(i,j)
j+=1
i += 1
What is the output of this code?
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print('*', end=' ')
print()
What is the output of this code?
rows = 5
# outer loop
while rows > 0:
# inner loop
cols = 3
while cols > 0:
# print star
print("*", end=" ")
# decrement cols by one
cols -= 1
# print new line
print()
# decrement rows by one
rows -= 1
Example
rows = 5
# outer loop
while rows > 0:
# inner loop
cols = 3
while cols > 0:
# print star
print("*", end=" ")
# decrement cols by one
cols -= 1
# print new line
print()
Question: Draw this pattern
# decrement rows by one without using nested loops.
rows -= 1
Some Loop Questions
Write a python program that accepts a positive number and prints the sum of the digits.

Write a python program that counts the frequency of a digit in a given number.
Eg. digit_counter(1223,2) -> 2

You might also like