Chapter 3 - Loops (Python)
Here's a concise walkthrough of the main ideas in Chapter 3, each with a small example.
while loops
A while loop repeats a block of code as long as its condition is True.
Example: print "Hello, world." five times.
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
An "annoying" while loop
You can keep asking for input until the user types exactly what you want.
Example: keep asking for "your name".
name = ''
while name != 'your name':
print('Please type your name.')
name = input('>')
print('Thank you!')
Infinite loops and break
while True: creates an infinite loop; break lets you exit early from inside the loop.
Example: same program using break.
while True:
print('Please type your name.')
name = input('>')
if name == 'your name':
break
print('Thank you!')
continue in loops
continue skips the rest of the loop body and jumps back to the top to recheck the condition.
Example: only "Joe" is asked for a password.
while True:
print('Who are you?')
name = input('>')
if name != 'Joe':
continue # go back to start of loop
print('Hello, Joe. What is the password? (It is a fish.)')
password = input('>')
if password == 'swordfish':
break # exit loop
print('Access granted.')
Truthy and falsey values, bool()
In conditions, 0, 0.0, and '' (empty string) are treated as falsey; almost everything else is truthy.
Example: use truthiness directly.
name = ''
while not name: # while name is empty
print('Enter your name:')
name = input('>')
print('How many guests will you have?')
num_of_guests = int(input('>'))
if num_of_guests: # means "if num_of_guests != 0"
print('Be sure to have enough room for all your guests.')
print('Done')
You can test truthiness with bool():
bool(0) # False
bool(42) # True
bool('') # False
bool('Hi') # True
for loops and range()
A for loop with range() repeats a fixed number of times, using the loop variable to step through the sequence.
Example: basic for loop with range(5).
print('Hello!')
for i in range(5):
print('On this iteration, i is set to ' + str(i))
print('Goodbye!')
Summing a series with for
You can accumulate a running total inside a loop.
Example: sum 0 to 100.
total = 0
for num in range(101): # 0..100
total = total + num
print(total) # 5050
while equivalent of a for loop
Anything done with for and range() can be done with while, though it's more verbose.
Example: while version of the loop.
print('Hello!')
i = 0
while i < 5:
print('On this iteration, i is set to ' + str(i))
i = i + 1
print('Goodbye!')
range() arguments: start, stop, step
range(stop), range(start, stop), and range(start, stop, step) let you control where counting starts, where it stops (up to but not including), and how much it changes each time.
Examples:
for i in range(12, 16): # 12, 13, 14, 15
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
for i in range(5, -1, -1): # 5, 4, 3, 2, 1, 0
print(i)
Importing modules
Modules are extra Python files that provide functions (standard library); you use them with import.
Example: random.randint in a loop.
import random
for i in range(5):
print(random.randint(1, 10)) # random int 1–10
You can import multiple modules at once:
import random, sys, os, math
Ending a program early with sys.exit()
sys.exit() immediately terminates the program, even if you're inside a loop.
Example: loop until the user types exit.
import sys
while True:
print('Type exit to exit.')
response = input('>')
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')
Short program: Guess the Number
This program uses random, a for loop, and break to let the user guess a secret number between 1 and 20, with up to 6 tries.
import random
secret_number = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
for guesses_taken in range(1, 7):
print('Take a guess.')
guess = int(input('>'))
if guess < secret_number:
print('Your guess is too low.')
elif guess > secret_number:
print('Your guess is too high.')
else:
break # correct guess
if guess == secret_number:
print('Good job! You got it in ' + str(guesses_taken) + ' guesses!')
else:
print('Nope. The number was ' + str(secret_number))
Short program: Rock, Paper, Scissors
This game uses nested while loops, random, and conditionals to play repeated rounds and track wins, losses, and ties.
import random, sys
print('ROCK, PAPER, SCISSORS')
wins = losses = ties = 0
while True: # main game loop
print(f'{wins} Wins, {losses} Losses, {ties} Ties')
# player input loop
while True:
print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
player_move = input('>')
if player_move == 'q':
sys.exit()
if player_move in ('r', 'p', 's'):
break
print('Type one of r, p, s, or q.')
if player_move == 'r':
print('ROCK versus...')
elif player_move == 'p':
print('PAPER versus...')
else:
print('SCISSORS versus...')
move_number = random.randint(1, 3)
if move_number == 1:
computer_move = 'r'
print('ROCK')
elif move_number == 2:
computer_move = 'p'
print('PAPER')
else:
computer_move = 's'
print('SCISSORS')
if player_move == computer_move:
print('It is a tie!')
ties += 1
elif ((player_move == 'r' and computer_move == 's') or
(player_move == 'p' and computer_move == 'r') or
(player_move == 's' and computer_move == 'p')):
print('You win!')
wins += 1
else:
print('You lose!')
losses += 1
Overall idea of the chapter
The chapter's core ideas are: use while for "loop while condition is true," for with range() for "loop a fixed number of times," control loops with break/continue, leverage modules like random and sys, and combine all of this to build small interactive games.