A Control flow enables us how to execute our code in order.
So far, all of our code can be seen as a finite and fixed sequence of commands.
For example:
# enter a sentence
sentence = input('Enter a sentence: ')
# print empty line
print()
# print the number of characters in the sentence
print('The sentence has',len(sentence),'characters.')
# split the sentence into words
words = sentence.split()
# print the number of words
print('The sentence has',len(words),'words.')
In the program above, basically five things happen every time you run it, regardless of what sentence the user inputs.
Control structures allow us to vary how many commands apply as a function of input.
The if control structure allows for conditional
application: some set of commands only apply if some condition holds.
For example:
sentence = input('Enter a sentence: ')
print()
print('The sentence has',len(sentence),'characters.')
if len(sentence) > 3:
print('That sentence has more than 3 characters!')
words = sentence.split()
print('The sentence has',len(words),'words.')
white spaces for delimiting scope or code blocks.# single if-statement on the same line
if 2+2 == 4: print('that was true')
# single if-statement indented on next line
if 2+2 == 4:
print('that was true')
# ANOTHER EXAMPLE
# example showing that Python uses whitespace to delimit scope
my_num = 11
if my_num > 10:
# INSIDE the if-block. Notice the four blank spaces.
result1 = my_num + 1
print(result1)
# OUTSIDE the if-block. Notice there are NO four blank spaces.
result2 = my_num + 3
print(result2)
def my_function(item):
item = item + 1
y = 3
res = item + y
return res
if True:
x = 5
y = 6
else:
x = 7
y = 8
for i in [1, 2, 3, 4]:
if i == 2 or i == 4:
x = "even"
else:
x = "odd"
class_names = ["Tom", "Alex", "Jeffery", "Ronald"]
# if the item is Tom, then print that's correct
if class_names[0] != "Tom":
print("that's correct")
else:
print("that's NOT correct")
# if the second itme is NOT Jeffery, then print, no this is Alex
if class_names[1] != "Jeffery":
print("No this is Alex")
# if the last item is Ronald, then print yes this an if statement example
if class_names[-1] == "Ronald":
print("this an if statement example")
if, else, and elif statements.
These allow you to specify that blocks of code are to be executed only if specified conditions are found to be true, or perhaps alternative code if the condition is found to be false.
if <expression_1>:
the code within this indented block is executed if..
elif <expression_2>:
the code within this indented block is executed if..
else:
the code within this indented block is executed.
colon character, and the body of each of these statements is delimited by whitespace.# Reacall the following code:
sentence = input('Enter a sentence: ')
print('The sentence has',len(sentence),'characters.')
if len(sentence) > 3:
print('That sentence has more than 3 characters!')
words = sentence.split()
print('The sentence has',len(words),'words.')
Depending on what sentence the user enters, a different number of commands apply; the last three statements only apply if the if-test evaluates to True.
The syntax of if is pretty straightforward. First, we have the keyword if, then some expression that evaluates to True or False, then a colon.
If there is only a single contingent command, it can occur on the same line or on the next. If it occurs on the next, it must be spaced or tabbed in from where the if occurs.
For example:
answer = input('yes or no? ')
if answer == 'yes':
print("That's a yes.")
if answer == 'no':
print("That's a no.")
answer = input('yes or no? ')
if answer == 'yes':
print("That's a yes.")
else:
print("That's a no.")
contingent statement, then they must occur on following lines and they must all be spaced or tabbed in the same amount.answer = input('yes or no? ')
my_list = []
if answer == 'yes':
print('That\'s a yes.')
print("That's not a no.")
# append the word `yes` to the list
my_list.append(answer)
print(my_list) #
not contingent
on the if test.answer = input('yes or no? ')
if answer == 'yes':
print('That\'s a yes.')
print("All done.")
must produce an error.#this produces an error!
answer = input('yes or no? ')
if answer == 'yes':
print('That\'s a yes.')
print("All done.")
More ...
You can have contingent if tests.
if test that only applies if the previous if test fails. if test that only applies if the previous if test succeeds. if tests in a row that don't care about each other.Here are examples of each:
word1 = input('Enter a word: ')
word2 = input('Enter another word: ')
if len(word1) > len(word2):
print('The first word is longer than the second.')
if word1 < word2:
print('The first word precedes the second alphabetically.')
word3 = input('Enter a word: ')
word4 = input('Enter another word: ')
if len(word3) > len(word4):
print('The first word is longer than the second.')
#special elif keyword!
elif word3 < word4:
print('The first word precedes the second alphabetically')
print('and is not longer.')
# nested if
word5 = input('Enter a word: ')
word6 = input('Enter another word: ')
if len(word5) > len(word6):
print('The first word is longer than the second.')
if word5 < word6:
print('The first word precedes the second alphabetically')
print('and is longer.')
else:
print("This does not work. 'r' comes after 'd'")
You can, of course, have any number of independent if structures in a row and any amount of embedding of them. As you might expect, you can have any number of elif clauses after an if.
Here are examples of each with one more level added:
#3 ifs in a row
word7 = input('Enter a word: ')
word8 = input('Enter another word: ')
if word7 < word8:
print('The first word precedes the second alphabetically.')
if len(word7) < len(word8):
print('The first word is shorter than the second.')
if word7[-1] == 's':
print("The first word ends in 's'.")
#1 if and 2 elifs
word9 = input('Enter a word: ')
word10 = input('Enter another word: ')
if word9 < word10:
print('The first word precedes the second alphabetically.')
elif len(word9) < len(word10):
print('The first word is shorter than the second,')
print('and does not precede it alphabetically.')
elif word9[-1] == 's':
print("The first word ends in 's',")
print('and does not precede the second alphabetically,')
print('and is not shorter than the second.')
# the pass keyword
if word9 < word10 and word9[-1] == 's':
pass
#double nesting of ifs
word11 = input('Enter a word: ')
word12 = input('Enter another word: ')
if word11 < word12:
print('The first word precedes the second alphabetically.')
if len(word11) < len(word12):
print('The first word is shorter than the second,')
print('and preceds the second alphabetically.')
if word11[-1] == 's':
print("The first word ends in 's',")
print('and precedes the second alphabetically,')
print('and is shorter than the second.')
if structure is else: a block of code that executes if the if or any elif clauses do not apply.elif.#else with no elif
word13 = input('Enter a word: ')
word14 = input('Enter another word: ')
if len(word13) < len(word14):
print('The first word is shorter than the second.')
else:
print('The first word is not shorter than the second.')
#else with elif
word15 = input('Enter a word: ')
word16 = input('Enter another word: ')
if len(word15) < len(word16):
print('The first word is shorter than the second.')
elif word15[-1] == 's':
print("The first word ends in 's',")
print('and is not shorter than the second.')
else:
print('The first word is not shorter than the second,')
print("and it does not end in 's'")