<Python tools> if, while and for statements
Topic 4: three control flow statements a programmer must know.
In topic 4, you will learn three control flow statements, that help you get the outcome with more efficient codes.
First, we need to know the structure of a compound statement!
A compound statement consists of one or more clauses.
What are clauses?
A clause consists a header and a suite.
Headers:
Suite
Each clause header begins with a uniquely identifying keywords (like if, while, for…) and end with a :
(colon). The suite is executed if the expression of the header is true.
Now let’s dig into the must-known control flow statements!
1. if statement
if...elif...else
statement is used for conditional execution. There can be zero or more elif
parts ( elif
is short for else if), and the else
is optional. This statement selects exactly one of the suites by evaluating the expressions one by one until one is found true; then that suite is executed. If all expressions are false, the suite of the else
clause is executed.
Let’s practice with an example:
The following codes show a list, assigned as basket, which consists of four types of fruits. Using input()
, a blank will show up and you can types in any kind of fruits. Then it will show wether the fruit is in the basket or not.
basket = ['apple', 'banana', 'kiwi', 'orange']
x = str(input('Enter a type of fruit:'))if x in the basket:
print(x + ' is in the basket.')
else:
print(x + ' is NOT in the basket')
2. While statement
The while
statement is used to repeat execution as long as an expression is true. break
statement and continue
statement are often used in the while statement.
Let’s practice with three examples:
(1) Print i
as long as i
is less than 6 and a message once the condition is false.
First, assign 1 to i
, and use +=
to add one to i after each while loop
. The loop will print i and a message once i
is more than 6.
i = 1
while i < 6:
print(i)
else:
print('i is no longer less than 6')
Result:
(2) Exit the loop when i
is 3. (Break statement)
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Result:
(3) Continue to the next iteration if i
is 3. (Continue statement)
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Result:
3. for statement
the for statement is used to iterate the elements of a sequence (such as string, list, tuples) or other repeatable objects.
Let’s practice with four examples:
(1) Print all of the numbers before 10 and exit the loop when i
is 7. (Break statement)
for i in range(10):
print(x)
if i == 7:
break
Result:
(2) Do not print 7.
for i in range(10):
if i == 7:
continue
print(i)
Result:
(3) Print all the numbers from 0 to 10, and print a message when the loop has ended.
for i in range(10):
print(i)
else:
print('Finally finished!')
Results:
Practice makes perfect!
Feel free to copy the codes and try them out by yourselves!