You are on page 1of 2

Beginner's Python

Numerical comparisons If statements


Testing numerical values is similar to testing string values. Several kinds of if statements exist. Your choice of which
to use depends on the number of conditions you need to

Cheat Sheet –
Testing equality and inequality test. You can have as many elif blocks as you need, and
>>> age = 18 the else block is always optional.

If Statements
>>> age == 18
True
Simple if statement
>>> age != 18 age = 19

and While Loops


False
if age >= 18:
Comparison operators print("You're old enough to vote!")
>>> age = 19
>>> age < 21
If-else statements
True age = 17
What are if statements? What are while loops? >>> age <= 21
True if age >= 18:
If statements allow you to examine the current state >>> age > 21 print("You're old enough to vote!")
of a program and respond appropriately to that state. False else:
You can write a simple if statement that checks one >>> age >= 21 print("You can't vote yet.")
False
condition, or you can create a complex series of if The if-elif-else chain
statements that identify the exact conditions you're
Checking multiple conditions age = 12
looking for.
You can check multiple conditions at the same time. The if age < 4:
While loops run as long as certain conditions remain and operator returns True if all the conditions listed are price = 0
true. You can use while loops to let your programs True. The or operator returns True if any condition is True. elif age < 18:
run as long as your users want them to. Using and to check multiple conditions price = 5
else:
>>> age_0 = 22 price = 10
Conditional Tests >>> age_1 = 18
A conditional test is an expression that can be evaluated as >>> age_0 >= 21 and age_1 >= 21 print(f"Your cost is ${price}.")
True or False. Python uses the values True and False to False
decide whether the code in an if statement should be >>> age_1 = 23
executed. >>> age_0 >= 21 and age_1 >= 21 Conditional tests with lists
True You can easily test whether a certain value is in a list. You
Checking for equality
A single equal sign assigns a value to a variable. A double equal
can also test whether a list is empty before trying to loop
Using or to check multiple conditions through the list.
sign (==) checks whether two values are equal.
>>> age_0 = 22 Testing if a value is in a list
>>> car = 'bmw'
>>> age_1 = 18
>>> car == 'bmw' >>> players = ['al', 'bea', 'cyn', 'dale']
>>> age_0 >= 21 or age_1 >= 21
True >>> 'al' in players
True
>>> car = 'audi' True
>>> age_0 = 18
>>> car == 'bmw' >>> 'eric' in players
>>> age_0 >= 21 or age_1 >= 21
False False
False
Ignoring case when making a comparison
>>> car = 'Audi' Boolean values
>>> car.lower() == 'audi'
True
A boolean value is either True or False. Variables with
boolean values are often used to keep track of certain
Python Crash Course
conditions within a program. A Hands-On, Project-Based
Checking for inequality
Simple boolean values Introduction to Programming
>>> topping = 'mushrooms'
>>> topping != 'anchovies' game_active = True nostarch.com/pythoncrashcourse2e
True can_edit = False
Conditional tests with lists (cont.) While loops (cont.) While loops (cont.)
Testing if a value is not in a list Letting the user choose when to quit Using continue in a loop
banned_users = ['ann', 'chad', 'dee'] prompt = "\nTell me something, and I'll " banned_users = ['eve', 'fred', 'gary', 'helen']
user = 'erin' prompt += "repeat it back to you."
prompt += "\nEnter 'quit' to end the program. " prompt = "\nAdd a player to your team."
if user not in banned_users: prompt += "\nEnter 'quit' when you're done. "
print("You can play!") message = ""
while message != 'quit': players = []
Checking if a list is empty message = input(prompt) while True:
players = [] player = input(prompt)
if message != 'quit': if player == 'quit':
if players: print(message) break
for player in players: elif player in banned_users:
Using a flag print(f"{player} is banned!")
print(f"Player: {player.title()}")
else: prompt = "\nTell me something, and I'll " continue
print("We have no players yet!") prompt += "repeat it back to you." else:
prompt += "\nEnter 'quit' to end the program. " players.append(player)

Accepting input active = True print("\nYour team:")


You can allow your users to enter input using the input() while active: for player in players:
statement. All input is initially stored as a string. message = input(prompt) print(player)
If you want to accept numerical input, you'll need to
convert the input string value to a numerical type. if message == 'quit': Avoiding infinite loops
active = False
Simple input Every while loop needs a way to stop running so it won't
else: continue to run forever. If there's no way for the condition to
name = input("What's your name? ") print(message) become False, the loop will never stop running. You can
print(f"Hello, {name}.") usually press Ctrl-C to stop an infinite loop.
Using break to exit a loop
Accepting numerical input using int() An infinite loop
prompt = "\nWhat cities have you visited?"
age = input("How old are you? ") prompt += "\nEnter 'quit' when you're done. " while True:
age = int(age) name = input("\nWho are you? ")
while True: print(f"Nice to meet you, {name}!")
if age >= 18: city = input(prompt)
print("\nYou can vote!")
Removing all instances of a value from a list
else: if city == 'quit':
print("\nYou can't vote yet.") break The remove() method removes a specific value from a list,
else: but it only removes the first instance of the value you
Accepting numerical input using float()
print(f"I've been to {city}!") provide. You can use a while loop to remove all instances
tip = input("How much do you want to tip? ") of a particular value.
tip = float(tip) Accepting input with Sublime Text Removing all cats from a list of pets
Sublime Text doesn't run programs that prompt the user for pets = ['dog', 'cat', 'dog', 'fish', 'cat',
While loops input. You can use Sublime Text to write programs that 'rabbit', 'cat']
A while loop repeats a block of code as long as a condition prompt for input, but you'll need to run these programs from print(pets)
is True. a terminal.
while 'cat' in pets:
Counting to 5 pets.remove('cat')
Breaking out of loops
current_number = 1 You can use the break statement and the continue
print(pets)
statement with any of Python's loops. For example you can
while current_number <= 5: use break to quit a for loop that's working through a list or a
print(current_number)
current_number += 1
dictionary. You can use continue to skip over certain items More cheat sheets available at
when looping through a list or dictionary as well. ehmatthes.github.io/pcc_2e/

You might also like