Intro to Control Structures
Control structures are programming concepts that let you control the flow of a program. The key types of control in modern software are decision-making structures and looping structures.
Decision-Making
The first decision-making mechanism we will learn is an if/then/else statement. These are very natural since the syntax matches well to our plain language. As with many languages Python uses ‘==’ for comparison, since the ‘=’ is reserved for assigning values to variables.
if name == 'John':
print('Welcome back, John!')
else:
print('Welcome to our site, {}'.format(name))
Looping
Looping is a common control structure that allows you to perform actions repeatedly.
For Loop
The first control function we are going to work with is a for loop. For loops can be used in many ways to loop across items:
- Loop a certain number of times using the ‘in range’ syntax. This loops
incrementing a counter, so printing the numbers 0 through 9:
for i in range(10): print(str(i))2) You an loop across a list of items
names = ['Bob', 'John', 'Joe'] for name in names: print('{}'.format(name)) - You an loop across a list of items
names = ['Bob', 'John', 'Joe'] for name in names: print('{}'.format(name))
While Loop
While loops are another kind of loop. While loops loop while a condition is True. So if you want to play a game until a user gets over 100 points:
while total_points <= 100:
points = play_round()
# Note the line below uses shorthand += which is the same as
# total_points = total_points + points
total_points += points
Exercise
To put this all together we will implement a madlib. What are the steps of building a madlib? The students should be able to frame this up independently, but something like this:
- Write a story
- Pull out the verbs/nouns/adjectives you want to make dynamic
- Ask the user to enter those words
- Print out the mad lib with the injected words
- Ask the user if they want to try again