top of page
top

Python 4a - If Statements 

noun-decision-3428301-FFFFFF.png

If Statements

Selection is one of three constructs of programming, along with Sequence (logical order) and Iteration (loops).

An if statement is a conditional statement that performs a specific action based on conditional values.

 

Essentially, if thing A is true, then thing B will happen.

If the user answers yes to the window question, then an appropriate statement is printed.

Double equals stands for ‘is equal to‘.

The colon stands for THEN and the line after an if statement must be indented (press tab key once).

answer = input("Is the window open? ")
if answer == "yes":
 
print("It's chilly in here!")

Is the window open? yes
It's chilly in here!

But what if the window is not open? At the moment nothing will happen if you type no:

Is the window open? no

The elif command stands for else if.

 

Essentially: If thing A is true then do thing B, else if thing C is true then do thing D:

But what about any other answer than yes or no? The else command will submit a response if the value is anything else.

 

The if and elif commands have a colon at the end, but else has it at the start. Also, else does not need to be on a new line.

answer = input("Is the window open? ")
if answer == "yes":
 
print("It's chilly in here!")

elif answer == "no":
  print("It's quite hot in here!")

answer = input("Is the window open? ")
if answer == "yes":
 
print("It's chilly in here!")

elif answer == "no":
  print("It's quite hot in here!")

else:

  print("I'm not sure what you mean.")

Is the window open? no

It's quite hot in here!

Is the window open? banana

I'm not sure what you mean.

If Statements Task 1 (Left or Right?)

Use an input line to ask the user whether they want to turn left or right.

Print a sentence of your choice if they chose left and a different sentence if they chose right.

Include an else statement in case the user doesn't input left or right.

Example solutions:

There is a path ahead. Do you turn left or right? left
The path turns and twists until it reaches a cliff. Dead end!

There is a path ahead. Do you turn left or right? right
A snake slithers across the path and bites your leg. Oh no!

There is a path ahead. Do you turn left or right? backwards
That's not an option!

Nested If Statements

Complex programs may require you to have if statements within if statements - when programming, one thing inside another is known as nesting.

 

You must make sure that the related if, elif and else statements line up with each other. Use the tab key to indent a line.

outer if

inner if

weather = input("What is the weather like today? ")
 

if weather == "sunny": 

   

    sunny = input("How hot is it? ")


    if sunny == "very hot":
       
print("Take some sunglasses with you!")
   
elif sunny == "cool":
       
print("Maybe take a jacket just in case?")
   
else:
       
print("Enjoy the sunshine!")

elif weather == "rainy":
 
print("Take an umbrella!")

else:
 
print("Have a good day!")

=

What is the weather like today? rainy
Take an umbrella!

=

What is the weather like today? sunny

How hot is it? cool

Maybe take a jacket just in case?

=

What is the weather like today? snowy
Have a good day!

=

What is the weather like today? sunny

How hot is it? very hot

Take some sunglasses with you!

If Statements Task 2 (Nested Ifs)

Use the weather program above as an example to help you write your own program with a nested if for at least one option.

Be careful to have your nested if's if, elif and else statements in line with each other.

Your program doesn't have to be about juice.

Example solutions:

Would you like orange, apple or tomato juice? orange
Would you like your orange juice smooth or with bits? smooth
One smooth orange juice coming up!

Would you like orange, apple or tomato juice? orange
Would you like your orange juice smooth or with bits? bits
A pulpy orange juice is on its way!

Would you like orange, apple or tomato juice? tomato
Yuck, you can't be serious?

Using Selection with Numbers

Comparison operators such as > (greater than) >= (greater than or equal to) < (less than) and <= (less than or equal to) can be used with if statements.

 

Logical operators such as and and or can also be used - more about them in section 4c.

When comparing a variable's value to a specific number, such as 50, don't forget to use double equals (==).

Python Comparison Operators

py9.png

score = int(input("Enter the maths test score: "))

 

if score == 50:
 
print("You scored top marks!")

 

elif score >= 40 and score < 50:
 
print("You scored a great grade!")

 

elif score >= 20 and score < 40:
 
print("You did okay in the test.")

 

else:
 
print("You have to try harder next time!")

=

Enter the maths test score: 50
You scored top marks!

=

Enter the maths test score: 43

You scored a great grade!

=

Enter the maths test score: 20

You did okay in the test.

=

Enter the maths test score: 13

You have to try harder next time!

If Statements Task 3 (Fastest lap)

A racing video game has a challenging track that players try to get a quick lap on. The current fastest lap time is 37 seconds.

Ask the player to enter their lap time and print a response based on their input.

You need individual responses for the following inputs:

  • Faster than 37 seconds.

  • Between 37 seconds and 59 seconds.

  • Between 60 seconds and 90 seconds.

  • Slower than 90 seconds.

Example solutions:

Enter your lap time: 35
You have set a new record!!!

Enter your lap time: 59
You did well this time!

Enter your lap time: 83
A little bit slow this time!

Enter your lap time: 110
Were you even trying!?! Hurry up!

Not Equal To

The opposite of equal to== ) is not equal to!= ).

 

!= is often used with while loops to repeat code while an input is not what is expected, for example repeatedly asking for a password while the input is not equal to "fluffythecat123". 

The code below uses != for an incorrect answer (although it could easily be re-written to use == for a correct answer).

answer = input("What is the capital of Eritrea? ")
if answer != "Asmara":
 
print("That is incorrect! It is Asmara.")

else:
  print("You got it right!")

=

What is the capital of Eritrea? Asmara
You got it right!

=

What is the capital of Eritrea? Windhoek
That is incorrect! It is Asmara.

If Statements Task 4 (True or False?)

Come up with your own true or false question that the user has to respond to. Depending on their answer, print whether they got it right or wrong.

You may want to use an if statement with == for a correct answer or != for an incorrect answer, there's multiple ways to write this program.

Example solutions:

There are 140 million miles between Earth and Mars. TRUE or FALSE? TRUE
That is correct! It is really that far!

There are 140 million miles between Earth and Mars. TRUE or FALSE? FALSE
You got it wrong, there really are 140 million miles between us!

bottom of page