0% found this document useful (0 votes)
19 views21 pages

Chapter6 - Iterative Statements

Uploaded by

TIẾN VŨ VĂN
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)
19 views21 pages

Chapter6 - Iterative Statements

Uploaded by

TIẾN VŨ VĂN
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/ 21

CHAPTER 6: ITERATIVE STATEMENTS

Lecture: Do Van Thanh


Phone: 0915463323
Email: [email protected]

©CMC Univ. 2022


Content

6.1. ‘while` loop


6.2. `for` loop
6.3. loop control statements
6.4. nested loops

©CMC Univ. 2022


1. while loop
• Loops are a basic concept in programming that you need to understand them
• Syntax:
while <boolean expression>:
<statements>
✓Like an `if` statement, the `while` statement tests a boolean expression, and if the
expression evaluates to `True`, it executes the code block below it.
✓Unlike the `if` statement, once the code block finished, the code "loops" back to
the boolean expression to test it again. If it still is `True`, the code block below it
gets executed once more.
✓ Like the `if` statement , if the boolean expression evaluates to `False`, the code
block below the `while` is skipped completely.
✓ Examples:

©CMC Univ. 2022


while loop

while <boolean expression>:


<statements>

©CMC Univ. 2022


while loop
▪ Write a program to print the numbers from 1 to n, where n is inputted from the
keyboard
def print_one_to_further(further):
num = 1
while num <= further:
print(num)
num += 1
print("Done")
further = int(input(“Enter the largest number to be printed: “))
print_one_to_further(further)
▪ Write a program to print the first 50 numbers divisible by 7.
def print_multiples_of_7(up_limit):
count = 1
while count <= up_limit:
print(count*7)
count += 1
print("Done")
print_multiples_of_23(50)
©CMC Univ. 2022
while loop
• Endless loops: when the boolean expression is always true
✓ can you spot errors without running the code below?
number = 1
total = 0
while (number * number) % 1000 != 0:
total += number
print("Total is", total)
✓Fix the code above so that it no longer is an endless loop
number = 1
total = 0
while (number * number) % 1000 != 0:
total += number
number +=1
print(number)
print("Total is", total)

©CMC Univ. 2022


2. ‘for’ loop
• Syntax: for <variable> in <collection>:
<statements>
✓while loops are more general than the the`for` loops;
✓ what a "collection" is ? There are many different kinds of collections. In later chapters
collections will be discussed in more detail.
• `for` loop with strings
def print_letters(text):
for letter in text:
print(letter)
print( "Done" )
text = str(input())
print_letters()

• What happens if the content of the variable `text` in the loop's code block is changed
?
©CMC Univ. 2022
‘for’ loop
• Example: def print_letters(text):
for letter in text:
print( letter )
if letter == "n":
text = "orange"
print( "Done" )
text = str(input())
print_letters(text)
✓As run this code, changing the contents of the variable `text` has *no effect* on the
result.
✓It means that no `for` loops are endless!
• `for` loop using a range of numbers
✓range(a): generates all integers, starting at zero, up to but not including the parameter.
✓range(a,b): a will be the starting number (default is zero), while b will be the "up to but not
including"
✓range(a, b, c): the third number c will be a step size (default is `1`)
©CMC Univ. 2022
`for` loop
• Example: def print3(a, b, c):
for x in range(a,b,c):
print(x)
a, b, c = input().split(“,”)
print(int(a), int(b), int(c))

• `for` loop with manual collections


for x in (10, 100, 1000, 10000, “mango”):
print(x)
for x in ("apple", "pear", 7, "orange", "banana", "mango", "cherry" ):
print(x)

©CMC Univ. 2022


3. loop control statements
• There are three extra statements controling the flow in a loop: else, break,
and continue.
• else: like an if statements, can add an else statements to the end a while or for
loop.
✓the else clause for a while loop
def count_up(i):
while i < n:
print(i)
i += 1
else:
print("The loop ends, i is now", i )
print( "Done" )
n=100
count_up(1)

©CMC Univ. 2022


loop control statements
✓ the else clause for a for loop
def print_fruits():
for fruit in ( "apple", "orange", "strawberry" ):
print(fruit)
else:
print("The loop ends”)
print("Done")

print_fruits()
• ‘break’ statement: allows to prematurely break out of a loop.
i = 1
while i <= 10000:
if i%9 == 0 and i%21 == 0:
break
i += 1
print (i, ": is our solution.")

©CMC Univ. 2022


loop control statements
✓ `break` in a program functions similarly to `return` in a function. We can write the above
code as a function and replace `break` with `return`, with the same effect
def joint_multiple():
i = 1
while i <= 10000:
if i%9 == 0 and i%21 == 0:
return i
i += 1

print (joint_multiple(), "is our solution.")

✓Exercise: we can pass the values 9 and 21 to the function as parameters, and make it
more general-purpose.
✓Note: the `break` statement also works for `for` loops. when a `break` statement is
encountered, and the loop also has an `else` clause, the code block for the `else` will
*not* be executed

©CMC Univ. 2022


loop control statements
Example:
for grade in ( 8, 7.5, 9, 6, 6, 6, 5.5, 7, 5, 8, 7, 7.5 ):
if grade < 5.5:
print( "The student fails!" )
break
else:
print( "The student passes!" )

©CMC Univ. 2022


loop control statements
• Continue statement: when thí statement is in a loop, the current cycle ends
immediately and the code loops back to the start of the loop.
✓ For the while loop, the boolean expression is evaluated again.
✓ For the for loop, the next item is taken from the collection and processed.
• Examples: Print all the numbers from 1 to n that are not divisible by 2 or 3, do
not end in 7 or 9.
n = int(input())
for num in range( 1, n):
if num%2 == 0:
continue
if num%3 == 0:
continue
if num%10 == 7:
continue
if num%10 == 9:
continue
print(num)
©CMC Univ. 2022
loop control statements
• Be very careful when using a continue statement in a `while` loop because this
statement would loop back to the boolean expression immediately and thus it
could cause an endless loop.
• Examples:
n= int(input())
i=0
while i < n:
print(i)
if i == 5:
continue
i += 1

©CMC Univ. 2022


4. nested loops
• You can put a loop inside another loop.
Def nestedloop(n):
for i in range(n):
print( "Entering the outer loop for i =", i )
for j in range(n):
print(“ Entering the inner loop for j =", j )
print(" ", i, ",", j)
print(“ Leaving the inner loop for j =", j )
print( "Leaving the outer loop for i =", i)
n = int(input())
nestedloop(n)

• Suppose that you want to write a function tat prints all pairs (i,j) where i and j can take on
the values 0 to maximum, but j must be higher than `i
def print_pairs(maximum):
for i in range( maximum ):
for j in range( i+1, maximum ):
print( " ", i, ",", j)
©CMC Univ. 2022
print_pairs(6)
nested loops
• You can also triple-nest loops, quadruple-nest loops, or go even deeper
def nested_loop3(n):
for i in range( 3 ):
for j in range( 3 ):
for k in range( 3 ):
print( i, ",", j, ",", k)
n = int(input())
nested_loop3(n)

©CMC Univ. 2022


What you learned
• What loops are

• `while` loops

• `for` loops

• Endless loops

• loop control via `else`, `break`, and `continue`

• Nested loops

©CMC Univ. 2022


Exercises
• Exercise 1: Review and rerun the examples in the lesson.
• Exercise 2: Write a function that prints a multiplication table using the while loops.
• Exercise 3: Write a function that prints a multiplication table using the for loops;
• Exercise 4: Write and test three functions that return the largest, the smallest, and the
number of dividables by predefined k in a given collection of numbers;
• Exercise 5: "99 bottles of beer" is a traditional song in the United States and Canada. It
is popular to sing on long trips, as it has a very repetitive format which is easy to
memorize, and can take a long time to sing. The song's simple lyrics are as follows: "99
bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98
bottles of beer on the wall." The same verse is repeated, each time with one fewer
bottle. The song is completed when the singer or singers reach zero. Write a function
that generates and prints all the verses of the song (though you might start a bit lower,
for instance with 10 bottles). Make sure that your loop is not endless, and that you use
the proper inflection for the word "bottle".
©CMC Univ. 2022
Exercises
• Exercise 6: The Fibonacci sequence is a sequence of numbers that starts with 1, followed by 1
again. Every next number is the sum of the two previous numbers. Write a function that calculates
and prints the Fibonacci sequence until the numbers get higher than a `maximum`.
• Exercise 7: A prime number is a positive integer that is dividable by exactly two different numbers,
namely 1 and itself. The lowest (and only even) prime number is 2. Write a function that returns
`True` if its parameter is a prime number, and `False` otherwise. Hint: In a loop where you test the
possible dividers of the number, you can conclude that the number is not prime as soon as you
encounter a number other than 1 or the number itself that divides it. However, you can *only*
conclude that it actually *is* prime after you have tested all possible dividers.
• Exercise 8: Write a function that prints all integers between the parameters `a` and `b` that can be
written as the sum of two squares. Produce output in the form of `z = x**2 + y**2`, e.g., `58 = 3**2
+ 7**2`. If a number occurs on the list with multiple *different* ways of writing it as the sum of two
squares, that is acceptable.
• Exercise 9: A, B, C, and D are all different digits. The number DCBA is equal to 4 times the number
ABCD. What are the digits? Note: to make ABCD and DCBA conventional numbers, neither A nor D
can be zero. Use a quadruple-nested loop
©CMC Univ. 2022
THANK YOU

©CMC Univ. 2022

You might also like