0% found this document useful (0 votes)
6 views8 pages

04-2 (Loop) Part 2

nbgfnsz

Uploaded by

Big Boss
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)
6 views8 pages

04-2 (Loop) Part 2

nbgfnsz

Uploaded by

Big Boss
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/ 8

Loops in Python

What is Loop?
Loops can execute a block of code number of times until a certain condition is met.
Their usage is common in programming. There are two types of loops in Python, for
and while.

1- for Loop:
A "for" loop is used for iterating over a sequence (such as a list, tuple, string, or
range) or other iterable objects. It executes a block of code for each item in the
sequence. The loop continues until all items in the sequence have been processed.

Syntax
for item in sequence:
# Code to execute for each item in the sequence

Example: Print out the numbers 1,2,3,4


# Print out the numbers 1,2,3,4 1234
for count in range(1,5):
print(count, end=" ")

o range(1, 5) generates a sequence of numbers starting from 1 and stopping


before 5. So, it includes the numbers 1, 2, 3, and 4.
o The "for" loop iterates over these numbers one by one, and for each iteration, the
value of count takes on one of these numbers.
o The print(count, end=" ") statement inside the loop prints each number and
uses end=" " to specify that a space should be added after each number.

Example: Calculate the sum of numbers from 0 to 4 (inclusive) and display both the
individual numbers and the total sum.
sum = 0
for count in range(5): 01234
sum = sum + count
print(count, end=" ") The sum is : 10
print("\nThe sum is : ", sum)

Dr. Khaldun Al- Moghrabi 2023-2024 Dr. Ali Al- Ghonmein


Example:
# Prints out the numbers 0,1,2,3,4
for count in range(5):
print(count, end=" ")

print()
# Prints out the numbers 3,4,5
for x in range(2, 6): 01234
print(x, end=" ")
2345
print()
# Prints out the numbers 2,4,6 246
for x in range(2, 8, 2):
print(x, end=" ") 9753

print()
# Prints out the numbers 9,7,5,3
for x in range(9, 1, -2):
print(x, end=" ")

Example:
name ="Sara"
for i in name : Sara Sara Sara Sara
print(name, end=" ")

Example:
name ="Sara"
for i in name : Sara
print(i, end=" ")
Example: Iterating over a list
name =["Khaldun","Ahmad","Mostafa","Ghazi"]

for i in name : Khaldun Ahmad Mostafa Ghazi


print(i, end=" ")

Example: Iterating over a string


message = "Hello, World!"
Hello, World!
for char in message:
print(char, end=" ")
Example: Iterating over a string
for x in "Ali": A
print(x) l
i

Dr. Khaldun Al- Moghrabi 2023-2024 Dr. Ali Al- Ghonmein


2- While Loop:
- A "while" loop is used to repeatedly execute a block of code as long as a specified
condition is true.

- The loop continues until the condition becomes false.

Syntax
while condition:
# Code to execute as long as the condition is true

Example: Print out the numbers 0,1,2,3,4,5

# using for 0 1 2 3 4 5
for count in range(6):
print(count, end=" ")

Example: Print out the numbers 0,1,2,3,4,5

# The equivalent code using while loops


count = 0 # Initialize count with 0 0 1 2 3 4 5
while count < 6:
print(count, end=" ") # Print the current value of x followed by a space
count += 1 # Increment x by 1

Exercise: Write the equivalent code using 'while' loops.

for x in range(2, 6):


print(x, end=" ")

print()

for x in range(1, 11, 2):


print(x, end=" ")

print()

for x in range(13, 1, -2):


print(x, end=" ")

Dr. Khaldun Al- Moghrabi 2023-2024 Dr. Ali Al- Ghonmein


break, continue Statement
The break Statement
- Breakpoint is a unique function in the for/while Loop that allows you to stop or
terminate the execution of the loop.

Example:
for x in range (1,20):
if (x%5 == 0): break 1 2 3 4
print(x, end=' ')

Example:
# Exit the loop when i is 3:

i = 1 1
while (i < 6):
2
print(i)
3
if i == 3 :
break The final value of i is 3
i += 1
print ("The final value of i is ", i)

The continue Statement


The 'continue' function, as the name indicates, will skip the current iteration of the
loop and continue with the execution of the remaining iterations.

Example:
for x in range (10,20):
if (x % 2 == 0) : continue 11 13 15 17 19
print(x, end = ' ')

Example:
# Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
1 2 4 5 6
if i == 3:
continue The final value of i is 6
print(i, end = ' ')

print("\nThe final value of i is ", i)

Dr. Khaldun Al- Moghrabi 2023-2024 Dr. Ali Al- Ghonmein


Nested Loops
Nested loops in Python refer to the situation where one loop is placed inside another
loop. This means that for each iteration of the outer loop, the inner loop will
complete all its iterations. Nested loops are useful when you need to perform
repetitive tasks that involve multiple levels of iterations.

Syntax: The basic structure of a nested for loop:

for outer_variable in outer_sequence:


# Outer loop code

for inner_variable in inner_sequence:


# Inner loop code

Syntax: The basic structure of a nested while loop:

while outer_condition:
# Outer loop code

while inner_condition:
# Inner loop code

Example:
for r in range(1, 5): 1
for c in range(r): 2 2
print(r, end=' ') 3 3 3
print() 4 4 4 4

o The outer for loop iterates over r from 1 to 4 (not including 5). This loop controls
the rows of the pattern.
o The inner for loop iterates over c from 0 to r - 1. This loop controls the number of
times the value of r is printed on the same line.
o print(r, end=' ') prints the value of i (the number) followed by a space, all on the
same line.
o print() is used to move to the next line, creating a new row in the pattern.

Dr. Khaldun Al- Moghrabi 2023-2024 Dr. Ali Al- Ghonmein


Example:
*
i= 1
while i<5: **
print(i*"*") ***
i +=1 ****

Example:

i= 1
*
while i<5:
print((5-i)*" ",i*"*") **
i +=1 ***
****

Example:
1 2
x = [1,3] 1 4
y = [2,4,6]
1 6
for i in x:
for j in y: 3 2
print(i, j) 3 4
print() 3 6

Example:
x = [1,3]
y = [2,4,6]
1 2
i = 0 1 4
while i < len(x) : 1 6
j = 0
while j < len(y) : 3 2
print(x[i] , y[j]) 3 4
j = j + 1 3 6
i = i + 1
print()

Dr. Khaldun Al- Moghrabi 2023-2024 Dr. Ali Al- Ghonmein


Example:
# Exit the loop when x is "Maan"

fruits = ["Amman","Irbid","Maan","Aqaba","Zarqa" ] Amman


Irbid
for x in fruits: Maan
print(x)
if x == "Maan":
break

Example:
# ignore banana using continue
fruits = ["apple","kiwi", "banana", "cherry"]
apple
for x in fruits: kiwi
if x == "banana": cherry
continue ;
print(x)

Example:
for x in [0, 1, 2]:
0 1 2
print (x, end = " ")

Example:
# Initialize the variables
start = 5
end = 10

# Write a loop for the range 5 to 10 5 6 7 8 9


for number in range(start, end):
print(number, end = " ")

Example:
st = {"Ali", "Mohammad", "Khaldun", "Ghazi"} # set creation

for item in st: Ali Mohammad Ghazi Khaldun


print(item, ,end = " ")

Example:
name = ["Sedra", "Dalia", "Lena", "Alissar"]

i = 0
while i < len(name): Sedra Dalia Lena Alissar
print(name[i], end = ' ')
i += 1

Dr. Khaldun Al- Moghrabi 2023-2024 Dr. Ali Al- Ghonmein


Exercise: Write a Python program to print the following patterns (using 'while' loops)

5 4 3 2 1 2 4 6 8 1 2 3 4 1

5 4 3 2 1 2 4 6 8 1 2 3 4 2

5 4 3 2 1 2 4 6 8 1 2 3 4 3

2 4 6 8 1 2 3 4 4

1 * * * * * * 1 2 3 4 5
2 * * * * * * 6 7 8 9 10
3 * * * * * * 11 12 13 14 15
4 * * * * * * 16 17 18 19 20
5 * * * * * * 21 22 23 24 25

5 5 5 5 5 *
1
4 4 4 4 *
2 2 *
3 3 3 *
3 3 3
*
2 2 *
4 4 4 4
1 *
5 5 5 5 5 *
*

5 *
**
4 4 ***
****
3 3 3 *****
2 2 2 2 ****
***
1 1 1 1 1 **
*

Dr. Khaldun Al- Moghrabi 2023-2024 Dr. Ali Al- Ghonmein

You might also like