Loop Structures
The for Loop
• A Python for loop has this general form:
for <var> in <sequence>:
<body>
• The <body> of the loop can be any sequence of Python statements
• <var> is called the loop index, which takes on each successive value in
<sequence>, and <body> is executed once for each value
• The <sequence> portion consists of a list of values
• E.g., range(n) is a built-in function in Python that generates “on the fly” a
sequence of numbers that starts at 0 and ends at n-1
The Flowchart of a for Loop
More items in No
<sequence>
Yes
<var> = Next item
<body>
Example 1: Average of a Series of Numbers
• Suppose we want to write a program that can compute the average of
a series of numbers entered by the user
• Here is an algorithm to do so:
Input the count of the numbers, n
Initialize sum to 0
Loop n times
Input a number, x
Add x to sum
Output average as sum/n
Example 1: Average of a Series of Numbers
• We can easily translate this algorithm into a Python implementation
def main():
n = eval(input("How many numbers do you have? "))
sum = 0.0
for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x
print("\nThe average of the numbers is", sum/n)
main()
Example 2: Printing Odd Numbers
• Suppose we want to write a program that prints odd numbers from 0
to n (inclusive), which can be input by a user
• Here is how the program can look like:
n = eval(input("Enter n: "))
for i in range(n+1):
if i % 2 == 1:
print(i, end = " ")
print()
Example 2: Printing Odd Numbers
• What if we want to print odd numbers from 1 (NOT 0) to n (inclusive),
which can be input by a user?
n = eval(input("Enter n: "))
for i in range(n+1):
if i == 0:
pass
else:
if i % 2 == 1:
print(i, end = " ")
print()
Example 2: Printing Odd Numbers
• What if we want to print odd numbers from 2 (NOT 1) to n (inclusive),
which can be input by a user?
n = eval(input("Enter n: "))
for i in range(n+1):
if i < 2:
pass
else:
if i % 2 == 1:
print(i, end = " ")
print()
Example 2: Printing Odd Numbers
• What if we want to print odd numbers from 3 (NOT 2) to n (inclusive),
which can be input by a user
n = eval(input("Enter n: "))
for i in range(n+1):
if i < 3:
pass
else:
if i % 2 == 1:
print(i, end = " ")
print()
Example 2: Printing Odd Numbers
• Is there a better way for doing this?
• Yes, we can use another version of range, namely, range(start, end)
s = eval(input("Enter the starting number: "))
e = eval(input("Enter the ending number: "))
for i in range(s, e+1):
if i % 2 == 1:
print(i, end = " ")
print()
Yet, Another Version of Range(.)
• We can even specify a different increment in the range(…) function
via including a third argument to it (i.e., range(start, end, step))
start = eval(input("Enter a starting number: "))
end = eval(input("Enter an ending number: "))
step = eval(input("Enter the step: "))
for i in range(start, end, step):
print(i, end = " ")
print()
Example 3: Fibonacci Sequence
• Suppose we want to write a program that computes and outputs the
nth Fibonacci number, where n is a value entered by a user
• The Fibonacci sequence starts with 0 and 1
• After these first two numbers, each number in the sequence is
computed as simply the sum of the previous two numbers
• E.g., 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
Example 3: Fibonacci Sequence
def fibonacci(n):
f_i = 0
f_j = 1
print(f_i, f_j, end = " ")
for k in range(2, n+1):
f_new = f_i + f_j
print(f_new, end = " ")
f_i = f_j
f_j = f_new
Example 3: Fibonacci Sequence
n = eval(input("Enter a number that is larger than 1 >> "))
if n < 2:
print("You can only enter a number that is larger than 1!")
else:
fibonacci(n)
Example 4: A Rectangle of Stars
• How can we write a program that draws the following shape of stars
using only 1 for loop and 1 if-else statement?
* * * * * * * * *
* *
* *
* *
* *
* *
* *
* *
* * * * * * * * *
Example 4: A Rectangle of Stars
• How can we write a program that draws the following shape of stars
using only 1 for loop and 1 if-else statement?
for i in range(9):
if i == 0 or i == 8:
x = "*********"
else:
x = "* *"
print(x)
Definite Loops vs. Indefinite Loops
• So far, we have considered only the case where the number of
iterations is determined before the loop starts
• This kind of loops is called definite loops and for is used in Python
to write definite loops
• But, what if we want to write loops, wherein we do not know the
number of iterations beforehand?
• This kind of loops is denoted as indefinite loops
The While Statement
• In Python, an indefinite loop is implemented using a while statement
while <condition>:
<body>
• <condition> is a Boolean expression, just like in if statements
• <body> is, as usual, a sequence of one or more statements
The Flowchart of a While Loop
Is <condition> No
True?
Yes
<body>
Revisiting Average of a Series of Numbers
• Here is how we have done it before:
def main():
n = eval(input("How many numbers do you have? "))
sum = 0.0
for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x
print("\nThe average of the numbers is", sum/n)
main()
Revisiting Average of a Series of Numbers
• Here is how we can do it now using a while statement:
sum = 0.0
n = eval(input("How many numbers do you have? "))
count = 0
while count < n:
x = eval(input("Enter a number >> "))
sum = sum + x
count = count + 1
print("The average of the " + str(n) + " numbers you entered is ", sum/n)
Revisiting Average of a Series of Numbers
• Here is also another version that assumes no prior knowledge about
the quantity of numbers the user will input
sum = 0.0
count = 0
moreData = "yes"
while moreData == "yes":
x = eval(input("Enter a number >> "))
sum = sum + x
count = count + 1
moreData = input("Do you have more numbers (yes or no)? ")
print("The average of the " + str(count) + " numbers you entered is ", sum/count)
Printing Odd Numbers With Input Validation
• Suppose we want to print the odd numbers between two user-input
numbers (inclusive), say, start and end
• The program assumes some conditions, whereby the start and end
numbers shall be positive and end should be always greater than start
• Hence, we should continue prompting the user for the correct input
before proceeding with printing the odd numbers
• This process is typically called input validation
• Well-engineered programs should validate inputs whenever possible!
Printing Odd Numbers With Input Validation
1. while True:
2. start = eval(input("Enter start number: "))
3. end = eval(input("Enter end number: "))
4. if start >=0 and end >= 0 and end > start:
5. break It breaks the loop; execution continues at line 8.
6. else:
7. print("Please enter positive numbers, with end being greater than start")
8.
9. for i in range(start, end + 1):
10. if i % 2 == 0:
11. continue It skips one iteration in the loop; execution
12. print(i, end = " ") continues back at line 9.
Nested Loops
• Like the if statement, loops can also be nested to produce
sophisticated algorithms
• Example: Write a program that prints the following rhombus shape
*
* *
* *
* *
* *
* *
* *
* *
*
The Rhombus Example
• One way (not necessarily the best way!) to think about this problem is to
assume that the stars are within a matrix with equal rows and columns
1 2 3 4 5 6 7 8 9
1 *
2 * *
3 * * Can you figure
4 * * out the different
5 * * relationships
6 * * between rows
7 * * and columns?
8 * *
9 *
The Rhombus Example
• One way (not necessarily the best way!) to think about this problem is to
assume that the stars are within a matrix with equal rows and columns
1 2 3 4 5 6 7 8 9
1 *
2 * *
Print a star when:
3 * *
1) Row + Column == 6
4 * *
5 * *
2) Row + Column == 14
6 * *
3) Row – Column == 4
7 * * 4) Column – Row == 4
8 * *
9 *
The Rhombus Example
• Here is one way of writing the program in Python
for i in range(1, 10):
for j in range(1, 10):
if ((i+j== 6) or (j-i==4) or (i+j == 14) or (i-j==4)):
print("*", end = "")
else:
print(" ", end = "")
print()
Can you generalize this code?
The Rhombus Example
• What are 6, 14, 4, and 4 below?
1 2 3 4 5 6 7 8 9
1 *
2 * *
Print a star when:
3 * *
4 * *
1) Row + Column == 6
5 * *
2) Row + Column == 14
6 * * 3) Row – Column == 4
7 * * 4) Column – Row == 4
8 * *
9 *
The Rhombus Example
• What are 6, 14, 4, and 4 below?
1 2 3 4 5 6 7 8 9
1 *
2 * *
Print a star when:
3 * *
4 * *
1) Row + Column == 6 (i.e., Columns/2 +2)
5 * *
2) Row + Column == 14 (i.e., Columns + 𝑹𝒐𝒘𝒔/𝟐 )
6 * * 3) Row – Column == 4 (i.e., Columns/2)
7 * * 4) Column – Row == 4 (i.e., Columns/2)
8 * *
9 *
The Rhombus Example: A More General Version
while True:
rows = eval(input("Enter number of rows: "))
columns = eval(input("Enter number of columns: "))
if rows != columns or rows % 2 != 1 or columns % 2 != 1:
print("Please enter odd and equal rows and columns")
else:
break
rows = abs(rows)
columns = abs(columns)
The Rhombus Example: A More General Version
for i in range(1, rows+1):
for j in range(1, columns+1):
if ((i+j== (columns//2 +2)) or (j-i==(columns//2)) or (i+j ==
(columns+ [Link](rows/2))) or (i-j==(columns//2))):
print("*", end = "")
else:
print(" ", end = "")
print()