Skip to content

A4 - if Statements

An if statement is used if we want to run a certain chunk of code only under certain conditions.

Here's an example that uses two if statements:

age = int(input("How old are you? "))

if age >= 18:
    print("You are an adult")

if age < 18:
    years_to_go = 18 - age
    print("You will be an adult in", years_to_go, "years.")

print("You will see this no matter how old you are.")

The general format is as follows:

if boolean_expression:
    first_thing_I_want_to_only_do_sometimes
    second_thing_I_want_to_only_do_sometimes
    etc

back_to_things_I_want_to_do_all_the_time

The indented code will only run if the boolean expression evaluates to True. Once you stop indenting, the if statement is finished and the code will run always.

Here's an example that uses a string variable:

fav = input("What's your favourite school subject?")

if fav == "Computer Science":
    print("That's pretty cool!")

Warning

When checking if two values are equal, remember that in Boolean expressions we use the double == sign. A common mistake is to use a single = instead.

Your Task

Create a file called a4.py for this assignment.

Write a text based program that contains some if statements. You should work with both numerical and string variables, and you should use a variety of Booelan operators: both == and !=, as well as at least one of <, >, <= or >=.

Example Scenario

If you're struggling to come up with a scenario that meets all the requirements, try something like this:

1. Ask the user to guess a secret number between 1 and 20
2. If they guessed 12, tell them they're correct
3. If they guessed less than 12, tell them they're too low
4. If they guessed more than 12, tell them they're too high
5. Ask the user to guess a secret word
6. If they guessed "pineapple", tell them they're correct
7. If they did NOT guess "pineapple", tell them they're incorrect