Conditionals & Loops
đź”— Boolean Operators
The operator ==
will tell you if two things are equal.
Note that one equal sign =
means “assignment” and two equals signs ==
means “test equal.”
If x
and y
are equal, x == y
will turn into True
.
If x
and y
are not equal, x == y
will turn into False
.
For example,
print(11 == 11)
print("hello" == "hello")
<
will tell you if the left thing is smaller than the right thing.
>
will tell you if the left thing is bigger than the right thing.
<=
and >=
will do exactly what you expect.
Challenges:
- Which of the following three are equal to
1111
?10 * 111
,57 * 33
, or11 * 101
-
Which is bigger,
123 * 45
or8765
? - How do you test whether a user said “yes” in their
input
?
đź”— if
, elif
, and else
Conditional statements (syntax: if
) allow your code to make decisions based on input.
Code inside an if
block is only executed if the test next to the if
evaluates to True
.
Note how whitespace at the beginning of a line determines which block a line of code is in.
print("duu du duu du dududu...")
print("duu du duu du dududu...")
if input("Is there something strange in your neighborhood? ") == "yes":
print("who ya gonna call??? ghostbusters!!")
The syntax elif
(else if) allows you to perform a subsequent test if the first if
doesn’t evaluate to True
.
The syntax else
is a catch-all that executes at the end of a series of if
and elif
tests if nothing else has triggered.
print("duu du duu du dududu...")
print("duu du duu du dududu...")
if input("Is there something strange in your neighborhood? ") == "yes":
print("who ya gonna call??? ghostbusters!!")
elif input("An invisible man... sleepin in your bed? ") == "yes":
print("who ya gonna call??? ghostbusters!!")
elif input("Mm.. if you've had a dose... of a freaky ghost baby? ") == "yes":
print("who ya gonna call??? ghostbusters!!")
else:
print("you better NOT call... ghostbusters!")
Challenge:
Ghostbusters is a PG-13 movie.
Ask the user for their age and then tell them if they’re ready to see Ghostbusters.
If they’re younger than thirteen, tell them no!
Else, if they’re older than 113, tell them that they’re the oldest person in the world.
Otherwise, tell them they’re cleared to watch Ghostbusters.
Hint: input
returns a string, but you’re probably against 13 and 113, which are numbers!
đź”— while
and break
According to urban legend, saying “bloody mary” 13x into a mirror will summon a scary ghost. Here’s one way of doing that.
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
print("Bloody Mary!")
Pretty annoying, right?
The syntax while
repeats a block of code until the test next to it evaluates False
.
while input("Keep going?") == "yes":
print("Bloody Mary!")
We can make Python count to 13 for us.
The variable i
increases by one until it reaches 13.
i = 0
while i < 13:
print("Bloody Mary!", i)
i = i + 1
What if we want a way to back out of summoning the scary mirror ghost?
Python’s break
statement allows the programmer to end a loop.
Let’s put a break
statement inside an if
to stop the summoning if we get scared.
i = 0
while i < 13:
print("Bloody Mary!", i)
i = i + 1
if input("Scared yet??? ") == "yes":
print("ok let's stop")
break
đź”— for
and range
Programmers want to execute a code block n
times so often that Python gives us a way to do just that: a for
loop coupled with the function range(0,n)
.
Like so,
for i in range(0,13):
print("Bloody Mary!", i)
Conceptually, for
iterates over each element in
a collection — it puts each element in the collection one at a time into the variable i
.
The function range(0,n-1)
creates a collection with the numbers 0
through n-1
.
(This way, when code inside for i in range(n):
runs n
times.)
If we wanted the numbers 1 through 13 instead of 0 through 12, we would write range(1,14)
.
Comprehension Question: How many times will “Boo!” get printed?
for i in range(3):
for j in range(3):
print("Boo!")
Challenge: There’s one ghost in the first room. There’s two ghosts in the second room. There’s three ghosts in the third room… and so on and so forth. There’s thirteen rooms in this haunted 80’s penthouse. Can you use math and a loop to calculate how many ghosts we’re going to run into total?
đź”— Number Guessing Game
Let’s put it all together to make a number guessing game. Python will randomly choose a number and then we’ll make successive guesses until we get it. Each time we guess, Python will tell us if our guess was too low or too high.
đź”— Number guessing game solution
'''
guessing.py
Guessing game! Guess a number between (inclusive) 1 and 100.
Skills
- variables/user input
- looping
- generating random numbers
'''
import random
secret = random.randint(1, 101) # Question: why 101 instead of 100?
print('Secret is', secret) # sanity check our secret generator
while True:
guess = int(input('Guess my secret: '))
# (1) if user guessed correctly, they win!
if guess == secret:
print('YOU WON!! SUCH VICTORY!')
break
# (2) Can we give the player some hints?
# - What sorts of hints might we want to give a player?
if guess < 1 or guess > 100:
print('Hint: 1-100')
if guess > secret:
print('Too high')
else:
print('Too low')
print('End')
# Challenge: Get rid of the magic numbers (min secret value and max secret value)
# Challenge: Tell the user how many guesses it took them to win
# Challenge question: What's the optimal strategy for playing this game?
# SUPER CHALLENGE: Make input request safe from bad user input
# - e.g., with try/catch or isnumeric
|>> download num_guess_game.py
Alternatively, here’s a very similar (but slightly more complex example from our 2021 camp:
import random
# Use random.randint(lower_bound, upper_bound) to get a random integer!
target_num = random.randint(0, 100)
is_game_over = False # This is a boolean variable!
guesses_left = 5
guess_list = []
# Let the user continue guessing until:
# A. They get it right or
# B. They run out of guesses
while is_game_over == False:
# Get use input
guess_num = int(input("Please give me a number: "))
# Store guess for later
guess_list.append(guess_num)
# Give the user feedback on their guess
if guess_num > target_num + 10:
print("That's WAY too high!")
elif guess_num > target_num:
print("That's too high!")
elif guess_num < target_num - 10:
print("That's WAY too low!")
elif guess_num < target_num:
print("That's too low!")
else: # They got the number correct! Tell them and end the game!
print("Perfect! The number was: " + str(guess_num))
is_game_over = True
# Update the number of guesses remaining, and end if we ran out
if is_game_over == False:
guesses_left = guesses_left - 1
if guesses_left <= 0:
is_game_over = True
print("Nope! Too many guesses!")
# Stats about the user's guesses
print('Here were your guesses:')
print(guess_list)
print('Number of guesses:', len(guess_list))
print('End of program!')
đź”— Rock paper scissors
Extra Challenge: Can you write a program that lets two players play Rock, Paper, Scissors against eachother? Your program should request player 1 and player 2’s choices (rock, paper, or scissors), and determine whether player 1 wins, player 2 wins, or the two players tied.
đź”— Rock paper scissors solution
'''
Implements a one or two player game of rock-paper-scissors
'''
# Two-player version
print('Starting a game of ROCK-PAPER-SCISSORS')
# Get player 1's move
play = input('Player 1 move: ')
while play not in 'RPS' or len(play) != 1:
print('Bad move')
play = input('Player 1 move: ')
player_1_move = play
# Get player 2's move
play = input('Player 2 move: ')
while play not in 'RPS' or len(play) != 1:
print('Bad move')
play = input('Player 2 move: ')
player_2_move = play
# Determine a winner
# First, what are all of the possibilities?
# - What is the outcome of each?
# Question: How can we simplify (make it shorter) this code?
# - Tie:
# if player_1_move == player_2_move:
# print('Tie game')
if player_1_move == 'R' and player_2_move == 'R':
print('Tie game')
if player_1_move == 'R' and player_2_move == 'P':
print('Paper covers rock!')
print('Player 2 wins')
if player_1_move == 'R' and player_2_move == 'S':
print('Rock smashes scissors!')
print('Player 1 wins')
if player_1_move == 'P' and player_2_move == 'R':
print('Paper covers rock!')
print('Player 1 wins')
if player_1_move == 'P' and player_2_move == 'P':
print('Tie game')
if player_1_move == 'P' and player_2_move == 'S':
print('Scissors shred paper!')
print('Player 2 wins')
if player_1_move == 'S' and player_2_move == 'R':
print('Rock smashes scissors!')
print('Player 2 wins')
if player_1_move == 'S' and player_2_move == 'P':
print('Scissors shred paper!')
print('Player 1 wins')
if player_1_move == 'S' and player_2_move == 'S':
print('Tie game')
# Challenge: first to win three rounds
# Challenge: add ai player
# - static, random, copy-cat, opposite
|>> download rock_paper_scissors.py