Previous | Tutorial index | Next

Tutorial 1: The if Statement – Making a Single Decision

Learning Objective

To be able to use an if statement to run a code block only when a specific condition is True.

1. The Theory (Deep Dive)

What is a Condition?

In programming, a condition is any expression that Python can evaluate as either True or False. This data type is called a Boolean (named after George Boole).

The Flowchart of an if Statement

Visualizing code helps a lot. Here is how an if statement flows:

[ Start ] | v [Check Condition] | +----+----+ | | True False | | v | [Run Indented] | | | +----+----+ | v [Continue with rest of program]

Truthiness (Advanced but Important)

In Python, the if statement doesn't only work with True or False. It also checks for "truthiness":

Example:

if "Python": print("This will print, because a non-empty string is truthy!")

Beginner Tip: For now, always write clear comparisons (e.g., if age > 12:) rather than relying on truthiness, to make your code easier to read.

The Role of input() and Type Conversion

Incorrect (Causes an error or wrong logic):

age = input("Enter age: ") # age is a string, e.g., "15" if age > 12: # ERROR! Can't compare string to int. print("Teenager")

Correct:

age = int(input("Enter age: ")) # Converts to integer if age > 12: print("Teenager")

2. Syntax

if condition: # Code to run if condition is True do_something() # Code here runs regardless (outside the if block)

3. Expanded Code Examples

Example 1: Checking Weather

temperature = 30 if temperature > 25: print("It's a hot day! Drink water.") print("This line always runs.")

Output:

It's a hot day! Drink water. This line always runs.

Example 2: Skipping the Block

temperature = 20 if temperature > 25: print("It's a hot day!") # This is completely skipped print("Goodbye.") # This runs normally

Output:

Goodbye.

Example 3: Comparing Strings (Case Sensitivity)

Python comparisons are case-sensitive. "hello" is not the same as "Hello".

user_input = "Yes" if user_input == "yes": # Checks for lowercase 'yes' print("Confirmed!") print("Program ended.")

Output: Program ended. (Because "Yes" does not equal "yes").

Example 4: Checking if a Number is Even

number = 10 if number % 2 == 0: # % is the modulo operator (remainder after division) print(f"{number} is an even number.")

Output: 10 is an even number.

4. Common Comparison Operators (Cheat Sheet)

Operator Meaning True Example False Example
> Greater than 10 > 5 4 > 8
< Less than 3 < 7 9 < 2
>= Greater than or equal to 5 >= 5 4 >= 6
<= Less than or equal to 3 <= 3 7 <= 2
== Equal to (VALUE check) "Hi" == "Hi" "Hi" == "hi"
!= Not equal to 5 != 3 5 != 5

Critical Rule: = is for assigning a value (e.g., x = 10). == is for checking if two things are equal. Never mix them up inside an if!

5. Common Pitfalls

  1. The Missing Colon (:)

  2. Inconsistent Indentation

  3. Comparing Different Data Types

  4. Floating Point Precision

6. Quizzes (Quick Knowledge Check)

Q1: Which keyword starts a conditional statement in Python?

Answer(B) `if`

Q2: The code inside an if statement must be __________ to the right.

Answer(B) indented

Q3: The expression "apple" == "Apple" evaluates to:

Answer(B) `False`

Q4: What is the output of:

score = 85 if score >= 90: print("A") print("Done")
Answer(B) `Done`

Q5: What is printed?

x = 0 if x: print("Hello") print("World")
Answer(B) `World` only (0 is falsy)

7. Hands-on Practice Exercises

Exercise 1: Positive Numbers
Write a program that asks the user for a number. If the number is greater than 0, print "The number is positive."

Sample Solution
num = float(input("Enter a number: ")) if num > 0: print("The number is positive.")

Exercise 2: Letter Hunter
Ask for a word. If it contains the letter "z", print "This word has a 'z'!".

Sample Solution
word = input("Enter a word: ") if "z" in word: print("This word has a 'z'!")

Exercise 3: Divisible by 5
Ask for an integer. If it is divisible by 5, print "This number is a multiple of 5."

Sample Solution
num = int(input("Enter an integer: ")) if num % 5 == 0: print("This number is a multiple of 5.")

Exercise 4: Freezing Alert
Ask for a temperature in Celsius. If it is below 0, print "Warning: Freezing conditions!"

Sample Solution
temp = float(input("Enter temperature (°C): ")) if temp < 0: print("Warning: Freezing conditions!")

Exercise 5: Adult Check
Ask for age. If 18 or older, print "You are eligible to vote."

Sample Solution
age = int(input("Enter your age: ")) if age >= 18: print("You are eligible to vote.")

8. Homework Assignment

This homework combines code prediction, bug fixing, and writing original programs. Submit your .py files or written answers.

Part A: Code Predictor (No Computer!)

Write down the exact output of the following snippets without running them.

Snippet 1:

price = 100 if price > 50: print("Expensive") print("Checkout")
Answer ``` Expensive Checkout ``` **Explanation:** The condition `price > 50` is `True` (100 > 50), so the `if` block runs and prints `"Expensive"`. The line after the `if` block is not indented, so it always runs and prints `"Checkout"`.

Snippet 2:

name = "Alice" if name == "alice": print("Welcome back, Alice!") print("System ready.")
Answer ``` System ready. ``` **Explanation:** The condition `name == "alice"` is `False` because `"Alice"` (capital 'A') is not equal to `"alice"` (lowercase 'a'). Therefore, the `if` block is skipped, and only the final `print` executes.

Snippet 3:

count = 5 if count: print("There are items.") else: # Wait, there is no else! Let's just see what happens. pass print("Done")
Answer ``` There are items. Done ``` **Explanation:** The variable `count` is `5`, which is a non‑zero number and therefore **truthy**. So the `if` block runs and prints `"There are items."`. The `else` block is skipped entirely (the `pass` is a placeholder that does nothing). Finally, `print("Done")` runs.

Part B: Bug Hunter

The following programs have syntax errors or logic errors. Fix them so they run correctly. Explain what was wrong and write the corrected version.

Buggy Code 1:

user_age = input("Enter age: ") if user_age >= 18 print("Adult")
Answer

Problems:

  1. Missing colon : after the if condition.
  2. input() returns a string, but we are comparing it to an integer (18) – this causes a TypeError.

Corrected Code:

user_age = int(input("Enter age: ")) if user_age >= 18: print("Adult")

Buggy Code 2:

temperature = 30 if temperature > 25 print("It's warm.")
Answer

Problems:

  1. Missing colon : after the if condition.
  2. The print statement is not indented – Python will raise an IndentationError because it expects a block inside the if.

Corrected Code:

temperature = 30 if temperature > 25: print("It's warm.")

Buggy Code 3:

answer = "Yes" if answer = "Yes": print("Confirmed")
Answer

Problem: Using the assignment operator = inside the if condition instead of the equality comparison operator ==. This will raise a SyntaxError.

Corrected Code:

answer = "Yes" if answer == "Yes": print("Confirmed")

Part C: Write a Program

Write complete Python programs for each of the following tasks. Use only the concepts covered so far (variables, input(), int(), and only if statements – no else or elif are allowed in these tasks).

Task 1: The Lucky Number Write a program that asks the user to guess a secret number. If the user guesses exactly 42, print "You guessed the secret number!". If they guess anything else, the program should simply end quietly (do nothing).

Sample Solution
guess = int(input("Guess the secret number: ")) if guess == 42: print("You guessed the secret number!")

Task 2: Password Strength Checker (Basic) Ask the user to create a password.

Sample Solution
password = input("Create a password: ") if password == "admin123": print("Secure password set.") if password == "": print("Password cannot be empty.")

Task 3: The Weekend Checker Ask the user for today's date as a number (e.g., 1 for Monday, 7 for Sunday). Using only if statements (one for Saturday, one for Sunday), print "It's the weekend!" if the date is 6 or 7. Otherwise, print nothing.

Sample Solution
date = int(input("Enter today's date (1=Mon, 7=Sun): ")) if date == 6: print("It's the weekend!") if date == 7: print("It's the weekend!")

Bonus Challenge (Optional)

Add a third if statement to Task 3 that prints "Invalid day" if the user enters a number outside the range 1 to 7.

Sample Solution
date = int(input("Enter today's date (1=Mon, 7=Sun): ")) if date == 6: print("It's the weekend!") if date == 7: print("It's the weekend!") if date < 1 or date > 7: print("Invalid day")

(Note: This uses or, which is covered in Tutorial 5 – a great preview!)

Summary Checklist

Before moving to Tutorial 2, ensure you can confidently answer:

Once you've finished the quizzes, exercises, and homework, you're ready for Tutorial 2: The if-else Statement. Happy coding!

Previous | Tutorial index | Next