28. Loops, II: while, break, continue¶
28.1. While loop¶
Earlier, we introduced a control statement, for loop, to repeatedly execute a set of commands, tell Python to "loop" back through a set of lines repeatedly. In this section, we will introduce another control statement which serves the same purpose, namely a while loop.
The basic syntax in Python of a while loop is the following:
while <some condition> :
<some commands to repeat>
<other commands>
The while loop runs as long as <some condition>
evaluates to True and executes the program block inside the loop (<some commands to repeat>
). <some condition>
is checked
every time at the beginning of the loop and whenever it evaluates to False, the loop immediately stops. The following example prints the digits 1 to 5.
x = 1;
while (x < 6):
print(x)
x += 1
28.2. Break statement¶
The break statement is used to exit a loop so can be used within both for
and while
loops. The purpose of this statement is to end the execution of the loop mmediately and the program control goes to the first statement after and out of the loop. Here is the syntax.
while <some condition> :
<some commands to repeat>
if <other condition> :
break
<other commands>
for variable_name in sequence :
<some commands to repeat>
if <some condition> :
break
<other commands>
In the following example, the for loop breaks when the count value is 5. The print statement after the for loop displays the sum of first 5 elements (i.e 0+1+2+3+4 = 10).
count = 0
num_sum = 0
for num in range(10):
num_sum = num_sum + num
count = count + 1
if count == 5:
break
print("Sum of first ",count,"integers is: ", num_sum)
28.3. Continue statement¶
The continue statement is used in a loop to take the program control back to the top of the loop without executing the remaining statements inside the loop. Here is a simple example which uses a for loop and continue statement to display all numbers between 0 and 5 except the numbers 3 and 6.
for x in range(7):
if (x == 3 or x==6):
continue
print(x)
28.4. Practice¶
Write the first 100 integers in a form of a table with 20 rows and 5 columns.
Write a program that inputs an integer n and display a right angle isosceles triangle of height n with asterisks. For instance if n=5:
* ** *** **** *****
Write a program that inputs a string s and returns the first vowel in s and its position. For instance if s = tribulation, then the output is i and 3. Use the break statement to stop whenever a vowel is found.
Write a program that takes a string s and prints the letters of s except the vowels (make use of the continue statement)
Write a program that takes an email address and returns the username and the domain name. For instance if the email address is jtobioko@aims.ac.za, then the output should be jtobioko and aims.ac.za.
Write program that outputs the smallest integer such that
Write a program that simulates the following game: Spin a dice and count the number of spins until face 6 shows up for the first time.