if

Objective

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

  • Write Python code using if statements.

Introductory Problem

Write Python code that asks:

  • How many aunts do you have?

    • Assign the input to the variable aunts

  • How many uncles do you have?

    • Assign the input to the variable uncles

intro.py
aunts = int(input("How many aunts do you have? "))
uncles = int(input("How many uncles do you have? "))
print("I have",aunts,"aunts and",uncles,"uncles")

if

The if conditional statement can be True or False. When the if statement executes, the condition is tested and if it is true, the indented block of code is executed. Otherwise, it is skipped.

Indentation is Python's method for grouping statements.

Examples

Example 1

Ask the user for a number. Write if statements to determine.

  • if the number is positive.

    • Print positive

  • if the number negative

    • Print negative

  • if the number is 0

    • Print is zero.

num = int(input("Give me a number: "))
if num > 0:
    print(num, "is positive")
if num < 0:
    print(num, "is negative")
if num == 0:
    print(num, "is zero")

Example 2

Ask the user if it is hot today.

  • If the user enters "Yes", print "The summer is always hot!"

  • If the user enters "No", print "It's time to move!".

hot = input("Is it hot today? ")
if hot == "Yes":
    print("It's always hot!")
if hot == "No":
    print("It's always cold!")

Example 3

Ask the user how much money they have.

  • If the user enters 99.99 or more, print "You're rich!"

  • If the user enters less than 99.99, print "You're not rich!"

money = float(input("How much money do you have? "))
if money >= 99.99:
    print("You're rich!")
if money < 99.99:
    print("You're not rich!")

Example 4

Using the code from the Introductory Problem

  • If the user has more aunts than uncles

    • Print "You have more aunts than uncles"

  • If the user has more uncles than aunts

    • Print "You have more uncles than aunts"

  • If the user has the same number of aunts and uncles

    • Print "You have the same number of aunts and uncles

  • If the user does not have the same number of aunts and uncles

    • Print "You do not have the same number of aunts and uncles

uncles = int(input("How many uncles do you have? "))
aunts = int(input("How many aunts do you have? "))
if aunts > uncles:
    print("You have more aunts than uncles")
if aunts < uncles:
    print("You have more uncles than aunts")
if aunts == uncles:
    print("You have the same number of aunts and uncles")
if aunts != uncles:
    print("You do not have the same number of aunts and uncles")

Last updated