Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† PYTHON FUNDAMENTALS LEVEL 1 PROFESSIONAL ยท Lesson 8 of 9

Module Seven

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
8
Module 7: Python Conditional Statements Module 7: Python Conditional Statements

MODULE 7: PYTHON CONDITIONAL STATEMENTS

Course: Python Fundamentals Level 1 Professional
Module: 7 of 8
Level: Beginner

1. Introduction to Conditional Statements

Imagine you are writing a school examination. Your teacher checks your score to determine whether you passed or failed.

If your score is 50 or above, you pass. If your score is below 50, you fail.

This is an example of decision-making. A decision depends on whether a particular condition is true or false.

Python can make decisions using conditional statements.

Conditional statements allow a program to perform different actions depending on whether a condition is True or False.

For example:

score = 75

if score >= 50:
    print("Congratulations! You passed.")

Output:

Congratulations! You passed.

Python checks whether the score is greater than or equal to 50. Because the condition is True, it displays the congratulatory message.

2. Learning Objectives

By the end of this module, you should be able to:

  • Explain what conditional statements are.
  • Understand how Python makes decisions.
  • Use the if statement.
  • Use if...else statements.
  • Use if...elif...else statements.
  • Combine conditions using logical operators.
  • Understand nested conditional statements.
  • Use comparison operators in conditions.
  • Build simple decision-making programs.

3. What Is a Condition?

A condition is an expression that Python evaluates to determine whether something is True or False.

For example:

age = 18

print(age >= 18)

Output:

True

The condition is True because 18 is equal to 18.

Another example:

score = 40

print(score >= 50)

Output:

False

The condition is False because 40 is less than 50.

4. The if Statement

The if statement tells Python to perform an action only when a condition is True.

Basic structure:

if condition:
    statement

The condition is checked first. If it is True, Python executes the indented statement. If it is False, Python skips that statement.

Example 1: Checking a Student's Score

score = 80

if score >= 50:
    print("You passed the examination.")

Output:

You passed the examination.

Example 2: Checking Age

age = 20

if age >= 18:
    print("You are an adult.")

Output:

You are an adult.

If the age were 15, Python would not display the message because the condition would be False.

5. The if...else Statement

Sometimes, you want your program to choose between two possible actions.

The if...else statement allows Python to perform one action when a condition is True and another action when it is False.

Basic structure:

if condition:
    statement_if_true
else:
    statement_if_false

Example: Pass or Fail Checker

score = 45

if score >= 50:
    print("Congratulations! You passed.")
else:
    print("Sorry, you failed.")

Output:

Sorry, you failed.

Because the score is 45, the condition is False. Python executes the code inside the else section.

Another Example: Checking Even or Odd Numbers

number = 7

if number % 2 == 0:
    print("This is an even number.")
else:
    print("This is an odd number.")

Output:

This is an odd number.

The modulus operator checks the remainder after dividing the number by 2. If the remainder is 0, the number is even. Otherwise, it is odd.

6. The if...elif...else Statement

What happens when a program needs to choose from more than two possibilities?

For example, a school may use the following grading system:

Score Grade
70 - 100 A
60 - 69 B
50 - 59 C
45 - 49 D
0 - 44 F

You can use if, elif and else to build a program that checks these conditions.

Basic structure:

if condition1:
    statement1
elif condition2:
    statement2
elif condition3:
    statement3
else:
    default_statement

The word elif means "else if". It allows Python to check another condition when the previous condition is False.

Example: Student Grading System

score = 75

if score >= 70:
    print("Grade A")
elif score >= 60:
    print("Grade B")
elif score >= 50:
    print("Grade C")
elif score >= 45:
    print("Grade D")
else:
    print("Grade F")

Output:

Grade A

Python checks the conditions from top to bottom. Once it finds a True condition, it executes the matching block and skips the remaining branches.

Important: Arrange your grading conditions carefully. Check the highest score ranges first so that students receive the correct grade.

7. Using Comparison Operators in Conditions

Comparison operators help Python compare values when making decisions.

Operator Meaning Example
== Equal to age == 18
!= Not equal to age != 18
> Greater than score > 50
< Less than score < 50
>= Greater than or equal to score >= 50
<= Less than or equal to score <= 50

Example: Checking Available Money

balance = 5000

if balance > 1000:
    print("You have enough money.")
else:
    print("Your balance is low.")

Output:

You have enough money.

8. Using Logical Operators in Conditions

Logical operators allow you to combine multiple conditions in a single decision.

Python has three main logical operators:

  • and
  • or
  • not

8.1 Using the and Operator

The and operator requires all combined conditions to be True.

Example: A student must score at least 50 and complete all required assignments to qualify for a certificate.

score = 75
assignment_completed = True

if score >= 50 and assignment_completed:
    print("You qualify for a certificate.")
else:
    print("You do not qualify yet.")

Output:

You qualify for a certificate.

8.2 Using the or Operator

The or operator returns True if at least one of the conditions is True.

Example: A student can access a school library using a student ID or a valid library card.

has_student_id = False
has_library_card = True

if has_student_id or has_library_card:
    print("Library access granted.")
else:
    print("Library access denied.")

Output:

Library access granted.

8.3 Using the not Operator

The not operator reverses a condition.

is_absent = False

if not is_absent:
    print("The student is present.")
else:
    print("The student is absent.")

Output:

The student is present.

9. Nested if Statements

A nested if statement is an if statement placed inside another if statement.

It allows a program to make a second decision after the first condition has been met.

Example: Checking Examination Eligibility

Imagine that a student must be registered and must have paid the examination fee before taking an examination.

is_registered = True
has_paid = True

if is_registered:
    print("Registration confirmed.")

    if has_paid:
        print("You can take the examination.")
    else:
        print("Please pay your examination fee.")

else:
    print("Please register first.")

Output:

Registration confirmed.
You can take the examination.

The first condition checks registration. If registration is confirmed, Python checks the second condition to determine whether the student has paid.

10. Checking Multiple Conditions with Range Comparisons

Python allows you to check whether a value falls between two numbers.

For example:

age = 15

if 13 <= age <= 19:
    print("You are a teenager.")
else:
    print("You are outside the teenage age range.")

Output:

You are a teenager.

This condition checks whether the age is at least 13 and no more than 19.

11. Understanding Indentation in Conditional Statements

Indentation means adding spaces at the beginning of a line of code.

Python uses indentation to identify which statements belong to an if, elif or else block.

Example of correct indentation:

score = 80

if score >= 50:
    print("You passed.")
    print("Well done!")

Both print statements belong to the if block.

Example of incorrect indentation:

score = 80

if score >= 50:
print("You passed.")

This code produces an indentation error because the statement inside the if block is not indented.

Remember: Use four spaces for each indentation level. Python programmers commonly follow this practice to keep code organised.

12. Practical Project: Student Result Checker

Project Description

You are creating a student result checker for a school. The program should collect a student's name and examination score, then display the appropriate grade and result.

Project Requirements:

  • Ask the student to enter their name.
  • Ask the student to enter their examination score.
  • Check whether the score is between 0 and 100.
  • Display Grade A for scores from 70 to 100.
  • Display Grade B for scores from 60 to 69.
  • Display Grade C for scores from 50 to 59.
  • Display Grade D for scores from 45 to 49.
  • Display Grade F for scores below 45.
  • Display an error message for scores outside the valid range.

Sample Solution

name = input("Enter student's name: ")
score = float(input("Enter examination score: "))

print("\n--- STUDENT RESULT ---")
print("Student Name:", name)

if score < 0 or score > 100:
    print("Invalid score. Enter a score between 0 and 100.")

elif score >= 70:
    print("Grade: A")
    print("Result: Excellent")

elif score >= 60:
    print("Grade: B")
    print("Result: Very Good")

elif score >= 50:
    print("Grade: C")
    print("Result: Good")

elif score >= 45:
    print("Grade: D")
    print("Result: Pass")

else:
    print("Grade: F")
    print("Result: Fail")

Example Interaction:

Enter student's name: Amina Yusuf
Enter examination score: 85

--- STUDENT RESULT ---
Student Name: Amina Yusuf
Grade: A
Result: Excellent

13. Practical Activities

Activity 1: Voting Age Checker

Write a program that asks a user to enter their age. If the age is 18 or above, display "You are eligible to vote". Otherwise, display "You are not yet eligible to vote".

Activity 2: Positive or Negative Number Checker

Ask a user to enter a number. Use conditional statements to determine whether the number is positive, negative or zero.

Activity 3: Discount Checker

Create a program that asks for the total shopping amount. If the amount is โ‚ฆ10,000 or more, display "You qualify for a discount". Otherwise, display "No discount available".

Activity 4: Password Checker

Ask a user to enter a password. Compare it with a predefined sample password. Display "Access granted" if they match and "Access denied" if they do not.

Activity 5: Largest Number Checker

Ask a user to enter two numbers. Use conditional statements to display the larger number. Also handle the situation where both numbers are equal.

14. Common Mistakes to Avoid

  • Forgetting the colon: Every if, elif and else statement must end with a colon.
  • Incorrect indentation: Statements inside conditional blocks must be indented.
  • Confusing = and ==: Use == when comparing two values.
  • Incorrect condition order: In grading programs, check higher score ranges before lower ones.
  • Using elif after else: An else block must come after all if and elif branches.
  • Forgetting input conversion: Convert numeric input using int() or float() before comparing it with numbers.
  • Ignoring invalid input: Consider how your program should respond when users enter values outside the expected range.

15. Key Terms to Remember

Term Meaning
Conditional Statement A statement that allows a program to make decisions.
Condition An expression that evaluates to True or False.
if Checks a condition and executes code when it is True.
else Executes code when the preceding if condition is False.
elif Checks another condition when previous conditions are False.
Nested if An if statement placed inside another if statement.
Indentation Spaces used at the beginning of a line to organise code blocks.
Boolean A data type that has two values: True and False.
Logical Operator An operator used to combine or reverse conditions.

16. Module Summary

In this module, you learned how Python makes decisions using conditional statements.

You explored the if, if...else and if...elif...else statements. You also learned how to combine conditions using logical operators, create nested conditions and use comparison operators to check information.

Conditional statements are important because they allow programs to respond differently depending on the information they receive.

You can use these skills to build grading systems, password checkers, shopping discount calculators, eligibility checkers and many other useful applications.

17. Knowledge Check

Test your understanding of Module 7 by answering the following questions.

1. What is the main purpose of conditional statements in Python?

  1. To make decisions based on conditions
  2. To install Python
  3. To create folders
  4. To delete variables

2. Which keyword is used to check a condition in Python?

  1. for
  2. if
  3. print
  4. input

3. Which keyword is used when the if condition is False?

  1. elif
  2. while
  3. else
  4. return

4. What does elif mean?

  1. Else if
  2. End loop
  3. Execute file
  4. Enter line

5. Which operator checks whether two values are equal?

  1. =
  2. !=
  3. ==
  4. >

6. Which logical operator requires all combined conditions to be True?

  1. or
  2. and
  3. not
  4. +

7. What is a nested if statement?

  1. An if statement inside another if statement
  2. An if statement without a condition
  3. A Python comment
  4. A type of variable

8. What does the not operator do?

  1. Adds two numbers
  2. Repeats a condition
  3. Reverses a Boolean value
  4. Displays a message

9. What must appear at the end of an if statement line?

  1. A comma
  2. A full stop
  3. A colon
  4. A question mark

10. What is indentation used for in conditional statements?

  1. To change a variable's value
  2. To identify which statements belong to a code block
  3. To install a package
  4. To close Python
Click here to reveal the answers
  1. A - Conditional statements allow programs to make decisions.
  2. B - The if keyword checks a condition.
  3. C - The else keyword handles the alternative when the if condition is False.
  4. A - elif means else if.
  5. C - == compares two values for equality.
  6. B - and requires all combined conditions to be True.
  7. A - A nested if is an if statement inside another if statement.
  8. C - not reverses a Boolean value.
  9. C - A colon ends the if statement line.
  10. B - Indentation identifies statements belonging to a code block.

18. What Is Next?

Module 8: Python Loops and Functions

In the final module, you will learn how to make Python repeat instructions and organise reusable blocks of code.

You will explore for loops, while loops and functions. You will also learn how to create simple programs that perform repeated tasks without writing the same instructions many times.

Congratulations! You have completed Module 7 of Python Fundamentals Level 1 Professional. Practise the examples and activities before moving to the final module.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’