Skip to content

3 – At a Crossroads

🎯 Learning Objectives

  • Use relational operators to form logical expressions
  • Use binary selection (ifelse statements) to control the flow of program execution
  • Generate and use random integers

💬 Key Vocabulary

  • Selection
  • relational operators,
  • logical (or Boolean) expressions
  • conditions
  • randomness
  • execution

📖 Selection in Python

  • Selection is when your programs check conditions and select the path of action that they will follow accordingly.

You will need an if or an if, else when there is more than one possible path for your program to follow.

📖 Worksheet – Practise using selection

  • Download this lesson’s worksheet to your Home Drive.

📖 Selection example

  • The condition will check if the value of user is equal to the string "Elizabeth".
  • The expression user == "Elizabeth" will evaluate to either True or False.
  • This is the if block, i.e. the code that will be executed if the condition is True.
  • This is the else block, i.e. the code that will be executed if the condition is False.
  • Only one of these blocks will be executed, depending on the value of the condition.

📖 Selection –  Syntax Pitfalls

  • It’s if and else. No capitals.
  • A colon : is always required after the if condition and after else.
  • Use indentation to indicate which statements ‘belong’ to the if block and the else block.
  • The == operator checks for equality. The single = is only used in assignments.
  • user is a variable. Don’t use quotes. "Elizabeth" is a string literal. It needs quotes.

📖 Relational operators in Python (comparisons)

You can use these operators to compare the values of expressions.

SymbolMeaningExamplesMeaning
==equal toa == 1Does a equal 1?
!=not equal tob != cAre b and c different?
<less thand < 3Is d less than 3?
<=less than or equal tod <= 3Is d at most 3?
>greater thand > 10Is d greater than 10?
>=greater than or equal tod >= 10Is d at least 10?
  • Expressions formed using these operators evaluate to either True or False.
  • You can also use these operators to compare alphanumeric values (strings).

In this lesson, you…

  • Used selection (if statements) to control the flow of program execution
  • Introduced elements of randomness into your programs

Next lesson, you will…

  • Explore how selection can handle more than two possible branches
  • Introduce iteration (while statements) to allow the flow of program execution to include loops

🏅 Level up

🥇 Level 1

  • Complete the Level 1 – Film Critic task and upload the worksheet to Teams.

🥈 Level 2

  • Complete the Level 2 – Lucky Number task and upload the worksheet to Teams.

🥉 Level 3

  • Complete the Level 3 – Eligible to Vote task and upload the worksheet to Teams.