0% found this document useful (0 votes)
8 views37 pages

Topic 5 - Repetition Structures_Student

The document outlines a programming course focused on Python, specifically covering repetition structures such as loops. It details the use of 'while' and 'for' loops, including their syntax, examples, and control statements like 'break' and 'continue'. Additionally, it provides exercises to reinforce the concepts learned.

Uploaded by

mrmghrby66
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)
8 views37 pages

Topic 5 - Repetition Structures_Student

The document outlines a programming course focused on Python, specifically covering repetition structures such as loops. It details the use of 'while' and 'for' loops, including their syntax, examples, and control statements like 'break' and 'continue'. Additionally, it provides exercises to reinforce the concepts learned.

Uploaded by

mrmghrby66
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/ 37

Imam Abdulrahman Bin Faisal University

Deanship of Preparatory Year and Supporting Studies

Basics of Programming through Python


Repetition Structure

Introduction to programming
COMP102
Term 2-2024-2025
Lesson Outcomes

▪ Write different types of loops, such as for, and while.


▪ Use loops to solve common problems, such as, finding sum,
finding max, etc.
▪ Select the correct type of loop based on a given problem.

2
Looping

▪ Looping is the process in which we have a list of statements that


executes repeatedly until it satisfies a condition.

▪ Python provides two kinds of loops :

▫ while loop
▫ for loop

3
while loop

▪ A while loop is a control flow statement that allows code to be executed


repeatedly while a given condition still holds true.
▪ Syntax:
While (condition):
Statements
▪ Three components that you need to construct the while loop in Python:
▫ The while: keyword.
▫ A condition: that is evaluated to either True or False; And
▫ A statements: block of code that you want to execute repeatedly

4
while loop

1. If the condition is false, exit the while statement


and continue execution at the next statement.
2. If the condition is true, execute the body and
then go back to step 1.
▪  The while loop is known as a pretest loop,
which means it tests its condition before
performing an iteration.

5
General way to write a while loop

Initialize your
• A variable is initialized outside of the loop Example: 1
counter
1 x=1
2 while x < 5:
• While loop executes while the condition is True
while
<condition>: 3 print(x)
4 x=x +1
• Executes the code within the block of code
Statements Output: 1
1
counter
• Counter is updated inside the loop 2
update 3
4

Instructions
• More instructions after the while loop(optional)

6
Updating variables

▪ Updating a variable by adding 1 is called an increment


i=i+1 or i += 1
▪ subtracting 1 is called a decrement
i=i-1 or i -= 1

7
Examples:
Example1: 1 Output: 1
x = 10 10
while (x != 0): 9
8
print(x)
7
x -= 1 6
5
Example2: 1 4
sum1 = 0 3
2
count = 1 1
while (count < 10):
sum1 = sum1 + count Output:
count += 1
print(count) 10
45
print(sum1)
8
Examples:
Example3: 1 ▪ Program
▪ Displaying “Thank you” 3 times # initialization
n = 1
n=1 # Condition of the while loop
while n <= 3:
print ("Thank you")
No While
Yes # Increment the value of the variable "n by 1"
n <=3 ? n=n+1

print (“Thank you”)


▪ Output
n = n +1 Thank you
Thank you
Thank you

9
Stop
An Infinite Loop (no counter update)
▪ Program
n=5
n = 5
No while n > 0:
While Yes
print ("Lather")
n > 0 ? print ("Rinse")
print('Lather') print ("Dry off")

print('Rinse')
▪ Output
Lather
Rinse
Lather
print('Dry off!') Rinse
... Will be infinitely displayed
and “Dry off” will never be displayed 10
Another loop
▪ Program
n=0
n = 0
No
while n > 0:
Yes
While n print ("Lather")
> 0 ? print ("Rinse")
print ("Dry off")
print('Lather')
▪ Output
print('Rinse') Dry off

This program will not display “Lather” and


“Rinse” because the logical expression on the
print('Dry off!')
while statement is False from the first iteration 11
The break statement
▪ The break statement ends ▪ Program
the current loop and jumps to
the statement immediately
following the loop.

▪ It is like a loop test that can


happen anywhere in the ▪ Output
body of the loop. Current x value : 10
Current x value : 9
Current x value : 8
Current x value : 7
Current x value : 6
Goodbye! 12
The continue statement

The continue statement ends the ▪ Program


current iteration and jumps to the top
of the loop and starts the next
iteration.

▪ Example:
Write a Python program to print odd numbers
▪ Output
from 1 to 10
1
3
5
7
9 13
Difference Between break and continue

BREAK CONTINUE
It terminates the execution of It terminates only the current iteration of
remaining iteration of the loop. the loop.

'break' resumes the control of the 'continue' resumes the control of the
program to the end of loop enclosing program to the next iteration of that loop
that 'break'. enclosing 'continue'.
It causes early termination of loop. It causes early execution of the next
iteration.
'break' stops the continuation of loop. 'continue' do not stops the continuation of
loop, it only stops the current iteration.

14
Output?

▪ Example1: ▪ Example2:
var = 10 var = 10
while var > 0: while var > 0:
print ('Current variable value :', var) var = var -1
var = var -1
if var == 5:
if var == 5:
continue
break
print ('Current variable value :', var)
print("Good bye!")
print ("Good bye!")

15
Try
Write a python program to ask the user to enter a valid response. If the user enter “yes” or “no”
the message: "Thank you for your response. " will be shown on the screen otherwise the message:
"Invalid response. Please try again.“ will be shown on the screen and ask the user to enter a valid
response.
Simple Run1:
Please enter a valid response: y
▪ Solution:
Invalid response. Please try again. while True:
Please enter a valid response: n user_input = input("Please enter a valid response: ")
Invalid response. Please try again.
if user_input == "yes“ or user_input == “no“ :
Please enter a valid response: yes
Thank you for your response. print("Thank you for your response.")
break
Simple Run2:
else:
Please enter a valid response: y
Invalid response. Please try again. print("Invalid response. Please try again.")
Please enter a valid response: n continue
Invalid response. Please try again.
Please enter a valid response: no 16
Thank you for your response.
for loop
▪ In Python, the for loop is designed to work with a sequence of data items.
When the statement executes, it iterates once for each item in the sequence.
Syntax:
for variable in [value1, value2, ...]:
statements
▪ The for statement executes in the following manner:
▫ The variable is assigned the first value in the list, then the statements
that appear in the block are executed.
▫ Then, variable is assigned the next value in the list, and the statements
in the block are executed again.
▫ This continues until variable has been assigned the last value in the list. 17
for loop
▪ Examples:

▪ Output: Su
Mo
1
2
Tu 3
We 4
Th 5
Fr
Sa

▪ The for-loop can be used on any type of iterable structure, such


as a list, tuple str, dict, or file.
18
for loop
▪ We can also use for loops for operations other than printing to a
screen.
▪ Example:

▪ Output:
30
19
for loop

▪ These loops are called “definite loops” because they


execute an exact number of times.
▪ Definite loops (for loops) have explicit iteration
variables that change each time through a loop.
These iteration variables move through the
sequence or set.
▪ We say that “definite loops iterate through the
members of a set”. 20
Example
▪ Program1: ▪ Program2:
friends = ["Ahmad", "Ali", "Saad"] for i in “great”:
for friend in friends : print(i)
print("Good Morning:", friend)
print('Done!')

▪ Output1: ▪ Output2:
Good Morning: Ahmad g
Good Morning: Ali r
Good Morning: Saad e
Done! a
t 21
range() function
▪ The range() function generates a list of numbers, which is generally
used to iterate over within for loops.
▪ Syntax: range(start, stop, step)
▪ Examples: for n in range(10): for n in range(1,10): for n in range(1,10,2):
print(n) print(n) print(n)
Output: Output: Output:
0 1 1
1 2 3
2 3 5
3 4 7
4 5 9
5 6
6 7
7 8
8 9
22
9
range() function
▪ Program 1: ▪ Output 1:
#
for j in range(4): #
print(“# “) #
#

▪ Program 2: ▪ Output 2:
# # # #
for j in range(4): To print in horizontal not vertical line
we use (end=“”)
print(“# “,end=“”)
23
Try out
▪ Output
▪ Write a program that displays the
Number Square
numbers 1 through 10 and their 1 1
respective squares. 2 4
3 9
4 16
5 25
▪ Solution:
6 36
7 49
8 64
9 81
10 100 24
Quiz
What will the following codes display?
Q1: for number in range(6):
print(number)

Q2: for number in range(2, 6):


print(number)

Q3: for number in range(0, 501, 100):


print(number)

Q4: for number in range(10, 5, −1):


print(number)
25
The pass statement

▪ The pass statement in Python is ▪ Example:


used when a statement is
required syntactically but you do
not want any command or code
to execute.
▪ Output:
▪ The pass statement is
Good bye
a null operation; nothing happens
when it executes.
26
The else statement in loop
▪ else can be used in for and while loops. The else body will be
executed when the loop’s conditional expression evaluates to false
▪ Program

▪ Output 0
1
2
3
4
27
else of for loop is executed
Counting the number of items in a list
▪ Program

▪ Output

Count: 6

28
Finding the largest –Maximum value in a list or sequence

▪ Program
• Before the loop, we set
largest to the constant
None.
• None is a special constant
value which we can store in
a variable to mark the
variable as “empty”

▪ Output
Largest: 74

29
Finding the smallest –Minimum value in a list or sequence

▪ Program

▪ Output
Smallest: 3

30
Nested for loop
▪ A nested loop is a loop that is inside another loop.
▪ Program:

▪ Output
# # # #
# # # #
# # # #
31
Nested for loop
▪ What will the below code produce?

▪ To get the total number of iterations of a nested loop, multiply the


number of iterations of all the loops.

32
Exercises

33
Exercise 1
Write a python program to print the square of all numbers from 0 to 10.

for i in range(11):
print("Square of",i,"=",i ** 2)

i=0
while i<=10:
print(“Square of", i,"=", I ** 2)
i = i + 1
34
Exercise 2
Write a python program to find the sum of all even numbers from 0 to 10.

SUM = 0 SUM = 0
for x in range(11): x = 0
if x % 2 == 0: while x <= 10:
SUM = SUM + x if x % 2 == 0:
print(SUM) SUM = SUM + x
x = x + 1
print(SUM)

35
Exercise 3
▪ Write a python program to read three numbers (a,b,c) and check how many
numbers between ‘a’ and ‘b’ are divisible by ‘c’. Note: use the highest value for a .
▪ Simple Run: Enter the three numbers:10,2,5
Between 2 and 10 there is 2 numbers divisible by 5 [5, 10]

a,b,c=eval(input(“Enter the three numbers:"))


x=0
L=[]
if a>b:
for i in range(b,a+1):
if i%c==0:
L.append(i)
x=x+1
print("Between",b,"and",a,"there is",x,"numbers divisible by",c,L)
36
Thanks!

37

You might also like