ICT582 Python Revision
🎯 Learning Objectives
πŸ“š Key Concepts

Basic if Statement

Executes a block only if the condition is True. Indentation (4 spaces) defines the block.

if condition:
    # runs when condition is True
    statement
score = 75
if score >= 50:
    print("Pass")

if-else Statement

One branch runs when condition is True, the other when it's False.

score = 40
if score >= 50:
    print("Pass")
else:
    print("Fail")

if-elif-else Chain

Checks multiple conditions in order β€” only the first matching branch runs.

score = 72
if score >= 80:
    grade = "HD"
elif score >= 70:
    grade = "D"
elif score >= 60:
    grade = "C"
elif score >= 50:
    grade = "P"
else:
    grade = "N"
print("Grade:", grade)   # Grade: D

Comparison Operators

OperatorMeaningExample
==Equal tox == 5
!=Not equal tox != 5
<Less thanx < 10
>Greater thanx > 10
<=Less than or equalx <= 10
>=Greater than or equalx >= 10

Logical Operators

OperatorMeaningExample
andBoth must be Truex > 0 and x < 10
orAt least one Truex < 0 or x > 100
notInverts True/Falsenot (x == 5)
age = 20
if age >= 18 and age <= 65:
    print("Working age")

Truthy and Falsy Values

In Python, the following values are considered False (falsy):

  • 0, 0.0 β€” zero numbers
  • "" β€” empty string
  • [], (), {} β€” empty collections
  • None
  • False

Everything else is True (truthy).

Nested if Statements

An if inside another if. Be careful with indentation.

age = 20
has_license = True

if age >= 18:
    if has_license:
        print("Can drive")
    else:
        print("Need a license")
else:
    print("Too young")

Chaining Comparisons

Python allows chained comparisons β€” very readable:

# Checks if 0 < x and x < 10
0 < x < 10        # Pythonic way

# Equivalent but longer:
x > 0 and x < 10  # Same result
πŸ’» Code Examples

Example 1 β€” BMI calculator with conditions

weight = float(input("Weight (kg): "))
height = float(input("Height (m): "))
bmi = weight / (height ** 2)

if bmi < 18.5:
    print("Underweight")
elif bmi < 25:
    print("Normal")
elif bmi < 30:
    print("Overweight")
else:
    print("Obese")

Example 2 β€” Using logical operators

username = input("Username: ")
password = input("Password: ")

if username == "admin" and password == "1234":
    print("Login successful")
else:
    print("Invalid credentials")
⚠️ Exam Focus
  1. Know that = is assignment, == is comparison β€” mixing them is a very common error.
  2. In an if-elif-else chain, only the first matching branch runs β€” order matters!
  3. Trace through nested if statements and identify exactly what gets printed for given inputs.
  4. Know logical operators: and requires both True; or needs at least one True.
  5. Indentation errors are syntax errors β€” be precise in exam code.
❌ Common Mistakes
⚑ Quick Recap
← Topic 02: Expressions Topic 04: Loops β†’