Programming · StudentHub Lesson

Conditionals

Learn how programs make decisions using if, elif, and else statements.

16 minBeginner
01

What you will learn

  • Write if, elif, and else statements in Python
  • Use comparison operators to build conditions
  • Combine conditions with and/or/not
  • Trace the flow of a conditional program
  • Avoid common conditional logic errors
02

Watch the lesson

Python for Beginners – Full Course [Programming Tutorial] · freeCodeCamp.org

Watch on YouTube
03

Topic notes

Main Idea

Conditionals let a program choose different actions depending on whether a condition is true or false.

Key Concepts

  • if runs code only when a condition is true
  • elif checks another condition if the first was false
  • else runs when none of the previous conditions were true
  • Comparison operators include ==, !=, >, <, >=, <=
  • Logical operators and/or/not combine multiple conditions

Definitions

  • Condition: an expression that evaluates to True or False
  • Comparison operator: symbols used to compare values
  • Logical operator: combines multiple boolean expressions

Syntax

```python

age = 16

if age >= 18:

print("Adult")

elif age >= 13:

print("Teenager")

else:

print("Child")

```

Examples

  • Checking if a number is even: if num % 2 == 0
  • Checking a password: if password == "1234"

Common Mistakes

  • Using = instead of == for comparison
  • Forgetting the colon at the end of if statements
  • Incorrect indentation of the code block
04

Key concepts

if/elif/else structureComparison operatorsLogical operatorsBoolean expressions
05

Important terms

Condition
An expression evaluating to True or False
elif
Keyword used to check another condition if the previous one was false
06

Worked examples

Problem

Write code to print 'Positive' or 'Negative' based on a number

  1. 1. num = -5
  2. 2. if num > 0: print('Positive')
  3. 3. else: print('Negative')

Answer: Negative

07

Quick revision

  • if runs when condition is True
  • elif checks additional conditions
  • else is the fallback case
  • == compares equality, = assigns values
  • Indentation defines code blocks in Python
08

Check your understanding

Question 1 · Multiple choice

Which operator checks if two values are equal in Python?

Question 2 · Multiple choice

What keyword runs code if none of the previous conditions were true?

Question 3 · True or false

You can have multiple elif statements in one if block.

Question 4 · Short answer

What will `if 5 > 3:` evaluate to?

Question 5 · Short answer

Fix this error: `if x = 5:`

Done with Conditionals?

Sign in to save your progress across the library.