Each line of your code is an instruction for Python to execute.
Python will execute the lines in order, from line 1 to the end of your file.
This is called sequence. It works for simple programs, but there are other ways to control the flow of your program.
Selection allows you to make decisions based on a test. Repetition allows you to run a section of code over and over.
Let's look at these ideas separately.
When you have a series of commands that you want to repeat, you're going to want to use a loop. Each time a loop runs, we call it an iteration.
There are two types of loops.
The for loop is used when you need to repeat your code based on a certain number of times. This is pseudo code:
for counter in range(start, stop): cool stuff happens here, as many times as the loop runs look, a 2nd line of cool stuffand finally, a line of code OUTSIDE the for loopWhat do you notice?
for loopcounter in range(0, 5): print('Hello')
What happened in the loop? The for loop needed a counter, that variable was called loopcounter. The for loop ran from the numeric range, 0 to 5. Each time it looped, the print() executed.
Check: to see if the counter variable is in the range
Do: do each indented line of code in the loop
Math: typically the counter variable goes up by one.
for loopcounter in range(0, 5): print(loopcounter)
What happened in the loop? The for loop ran five times. The amount of loops was controlled by the range(). Each time the loop ran, the variable loopcounter was printed with print(). Did you notice where the number started and left off? Most people, mistakenly, expect numbers to start at 1, not 0.
Let's look at helping those folks out in the next example.
for loopcounter in range(1, 6): print(loopcounter)That output looks better, doesn't it? But what is it telling us about numeric ranges?
for counter in range(1, 11): print(counter * 5)The data structure that I'm going to use in the next example is called a list. Don't worry about lists for now. Let's just use it.
Our first for loop examples have Python iterating across a range of numbers, using range(). Python can also loop across a set of data. It does all the counting for you:
caf_specials = [ 'breakfast sandwich', 'milk', 'rice', 'pizza', 'salad', 'fish and chips' ]for i in caf_specials: print(i)
What happened? Python took each item in the list, and held it in the variable i.
As the loop, looped, the print() printed whatever was in the variable i.
The loop ran for as many times as there were things in the list.
Python will do the same with a string.
my_string = "This is the most interesting sentence I could think of."for i in my_string: print(i)At this point in the course, for loops depend on the range(). It stands to reason that we should explore this built-in function.
#range([start], stop[, step])#start: Starting number of the sequence.#stop: Generate numbers up to, but not including this number.#step: Difference between each number in the sequence.for i in range(5): # only stop value provided print(i)print('')for i in range(0, 5): # start and stop value provided print(i)print('')for i in range(5, 0, -1): # start and stop and negative step value provided print(i)print('')for i in range(0, 6, 2): # start and stop and step value provided print(i)import turtle #import the turtle modulebob = turtle.Turtle() #create a turtle named bob#Let's draw a squarebob.forward(100) #forward movement 100 pxbob.left(90) #turn left 90 degreesbob.forward(100) #forward movement 100 pxbob.left(90) #turn left 90 degreesbob.forward(100) #forward movement 100 pxbob.left(90) #turn left 90 degreesbob.forward(100) #forward movement 100 pxbob.left(90) #turn left 90 degrees# Is there a way to draw the square using a loop?#Let's move bob away from his first squarebob.penup()bob.right(90)bob.forward(100)bob.pendown()for x in range(4): #loop instruction set bob.forward(100) #forward movement 100 px bob.left(90) #turn left 90 degreesWhich square solution looks more efficient? The one with the 8 commands, or the one with 2 commands in a loop?
A loop can be placed in another loop. This is called a nested loop.
for outer_loop_counter in range(0,4): print('OUT') for inner_loop_counter in range(0,4): print('In')
What do you notice?
The outer loop seems to run once, then the inner loop runs several times, and then the outer loop runs, then the inner loop runs several times.
Let's look at at that previous example, but modify the print(), so that you can see what's happening to the counters.
for outer_loop_counter in range(0,4): print('OUT', outer_loop_counter) for inner_loop_counter in range(0,4): print('IN', inner_loop_counter)Notice that the inner loop is reset?
What would a student's school week look like in a nested loop?
for day in range(0,5): print('A School Day Begins') for period in range(0,5): print('A School Period') print('A School Day Ends')import turtle #import the turtle modulebob = turtle.Turtle() #create a turtle named bobfor outerLoop in range(4): #OUTER loop bob.pencolor('red') #outer loop draw everything in red bob.forward(100) #forward movement 100 px bob.left(90) #turn left 90 degrees for innerLoop in range(2): #INNER loop bob.pencolor('black') #INNER loop, draw everyting in black bob.right(90) #turn right 90 degrees bob.circle(25) #draw circle with 25 px radiusIn the previous code, we can see the OUTER loop drawing the sides of a square.
When we get to a corner, the INNER loop draws 2 circles.
Then the INNER loop stops once the counter is out of the range.
Then OUTER loop continues.
These steps happen for as many times as the OUTER loop counter is in its range.
While loops are also known as conditional loops. While require a condition to be true. This condition is also known as a test.
Before we start learning about while loops, I'm going to show you how to stop an infinite loop. CTRL-c remember that.
x = 5while x == 5: print(x)
Well, that happened? That's a lot of 5's... Hope you remembered CTRL-c!
The while loop was set to run as long as x == 5.
If the operator == is confusing you, please take a moment to look at the operators note.
It turns out that x was set to 5 before the the loop, and x will remain 5 until, forever.
Let's try that again
x = 5while x > 0: print(x) x -= 1
In this example, x was set to 5 before the loop.
If the operators > or -= are confusing you, please take a moment to look at the operator note.
The while loop was set to run as long as x was greater than 0.
But, if you look in the loop, we are subtracting 1 from x on each rotation. Eventually, we get to the situation where 0 > 0 and the loop stops because the condition is false.
Sometime when I am talking about while loops, you'll hear me reference a flag. What I mean is a boolean that controls the while loop. Here's an example:
flag = Truewhile flag == True: print('Hello') userinput = input('Please input the word STOP, to stop this loop: ') if userinput == 'STOP': flag = False else: print('I guess this is not going to stop')import turtle #import the turtle modulebob = turtle.Turtle() #create a turtle named bobloopControl = Truewhile loopControl == True: bob.circle(50) bob.left(45) bob.forward(10) # Before you run this, ask yourself, will this ever end?As we have already discovered, for loops work well when your loops are based on counting, and while loops are very effective when you have a boolean expression (True or False).
How can we manage our loops based on other input?
userInput = input('Please enter a number: ')userInput = int(userInput)for counter in range(0, userInput): print(userInput)
z = Truewhile z: print('Hi') userInput = input('Please type Q to quit ') if userInput == "Q": z = Falsew = input('Please type in a number: ')w = int(w)for w in range(0, w): print(w)# Author: Mr. Liconti, based on Jack M.'s original code# Date: 2/9/2018# File Name: rect_area_MENU.py# Description: making a program to calculate the area of a rectangle. Added a Menu#import statments here#global variables hereflag = True #loop controlprint('This program will give you the area of a rectangle.')while flag == True: #Display menu options print(' MENU') print('==========') print('S to start') print('H for help') print('Q to quit') print('==========') print(' ') choice = input('Option?: ') #get user's choice if choice == 'H': print('This program will give you the area of a rectangle.') print('Please provide the height and width when asked.') print('You can quit this program from the main menu by pressing Q') elif choice == 'Q': flag = False elif choice == 'S': height = input('height: ') #this is where you input the height of the rectangle width = input('width: ') #this is where you input the width of the rectangle height = int(height) #changing height into a int because it will be a number width = int(width) #changing the width to a int because it will be a number area = height * width #area is equal to height times width area = str(area) #area is changing to a string because it was a int print('The answer is: ' + area + ' meters') #the area is in meters so you would #add meters to the end else: print('Not a valid choice. Only S, Q and H are valid choices')print('Program ending.')