if else

Objective

After working through this lesson, you’ll be able to

  • Write Python code using if else statements.

Introductory Problem

Write Python code that asks:

  • How many messages do you send to family per day

  • How many messages do you send to friends per day

Write if statements to determine if you send more or less messages to family or friends per day. Assume you do not send the same amount of messages to family or friends.

Introduction

Sometimes you’ll want a catchall for other conditional cases. If the conditional statement evaluates to False, the else is executed.

What's the difference between if and if/else?

  • If you use two if statements, Python will evaluate both if statements to determine if they are True.

  • With if/else, the else is executed only if the first condition is False.

  • An if/else is faster than two if’s. If the first statement is False, Python will execute the else block.

Generally, it's good programming practice to have an else. That way you know that the if part of the condition evaluated to False.

Example 1

Rewrite the Introductory Problem using if/else.

family = int(input("How many messages do you send to family? "))
friends = int(input("How many messages do you send to friends? "))
if family > friends:
    print("You send more messages to family")
else:
    print("You send more messages to friends")

Example 2

Write Python code that asks a user how many minutes do you ride the bus? What data type is the input?

If the user enters 30 or less, print “not bad”. Else, print “that’s a long time”.

mins = int(input("How many minutes do you ride the bus? "))
if mins <= 30:
    print("not bad")
else:
    print("that's a long time")

Example 3

Mr Cheng’s daughter visits his classroom and wants you to play Roblox with her.

Write Python code that asks do want to play Roblox with her?

If the user enters “YES”, print “Mr Cheng will give you extra credit”. (The “YES” in all caps is intentional)

Else print “Now Mr Cheng will have to play Adopt Me with her”.

play = input("Do you want to play Roblox with her? ")
if play == "YES":
    print("Mr Cheng gives you extra credit")
else:
    print("Now Mr Cheng will have to play Adopt Me with her")

Example 4

Write Python code that asks a user how much money they have. What data type is the input?

If the user enters 9.90 or more, print “you have enough to buy a shirt”. (do not enter $)

Else, print “you do not have enough money”.

money = float(input("How much money do you have? "))
if money >= 9.90:
    print("You have enough money to buy a shirt")
else:
    print("You do not have enough money")

Last updated