Python Programming for Beginners

Chapter 4: Conditional Statements – if, elif, and else

Chapter 4: Conditional Statements – if, elif, and else

4.1 Introduction

A program often needs to make decisions.

For example:

If a student scores enough marks, display "Pass".

If a person's age is 18 or above, allow registration.

If the temperature is high, display a warning.

If a password is correct, allow access.

Python provides conditional statements to make these decisions.

The main conditional statements are:

if

if...else

if...elif...else

Nested if

Conditional statements usually work together with comparison and logical operators.

4.2 What is a Conditional Statement?

A conditional statement allows a program to execute different code depending on whether a condition is true or false.

Basic structure:

if condition:    statement

Example:

age = 20 if age >= 18:    print("You are eligible.")

Output:

You are eligible.

The statement inside the if block executes because age >= 18 is True.

4.3 The if Statement

The if statement is the simplest decision-making statement in Python.

Syntax:

if condition:    statement

Example:

marks = 75 if marks >= 40:    print("Pass")

Output:

Pass

If the condition is false, Python simply skips the if block.

Example:

marks = 30 if marks >= 40:    print("Pass")

In this case, nothing is displayed because the condition is false.

4.4 Importance of the Colon

A colon : is required after the condition.

Correct:

if age >= 18:    print("Adult")

Incorrect:

if age >= 18    print("Adult")

Forgetting the colon results in a syntax error.

4.5 Indentation in Conditional Statements

Python uses indentation to identify the statements belonging to a conditional block.

Example:

age = 20 if age >= 18:    print("Adult")    print("Eligible to vote")

Both print() statements belong to the if block.

Statements outside the indentation are not part of that block.

age = 20 if age >= 18:    print("Adult") print("Program completed")

Here, "Program completed" executes regardless of the condition.

4.6 The if...else Statement

The else block executes when the if condition is false.

Syntax:

if condition:    statement_if_true else:    statement_if_false

Example:

age = 16 if age >= 18:    print("Adult") else:    print("Minor")

Output:

Minor

Only one of the two blocks is executed.

4.7 Example: Pass or Fail

marks = int(input("Enter your marks: ")) if marks >= 40:    print("Pass") else:    print("Fail")

If the user enters 65:

Pass

If the user enters 25:

Fail

This is a simple example of decision-making.

4.8 Example: Even or Odd

The modulus operator can be combined with a conditional statement.

number = int(input("Enter a number: ")) if number % 2 == 0:    print("Even") else:    print("Odd")

The expression:

number % 2 == 0

checks whether the number leaves a remainder of zero when divided by 2.

4.9 Example: Positive, Negative, or Zero

Sometimes there are more than two possibilities.

For example, a number can be:

Positive

Negative

Zero

We can use if, elif, and else.

number = float(input("Enter a number: ")) if number > 0:    print("Positive") elif number < 0:    print("Negative") else:    print("Zero")

4.10 The elif Statement

elif means else if.

It allows a program to test another condition when the previous condition was false.

Syntax:

if condition1:    statement elif condition2:    statement else:    statement

Example:

marks = 72 if marks >= 90:    print("Grade A+") elif marks >= 80:    print("Grade A") elif marks >= 70:    print("Grade B") else:    print("Needs improvement")

Output:

Grade B

Python checks the conditions from top to bottom.

As soon as it finds a true condition, the corresponding block is executed and the remaining elif conditions are skipped.

4.11 Multiple elif Conditions

A program can contain multiple elif statements.

Example:

marks = int(input("Enter marks: ")) if marks >= 90:    grade = "A+" elif marks >= 80:    grade = "A" elif marks >= 70:    grade = "B" elif marks >= 60:    grade = "C" elif marks >= 50:    grade = "D" else:    grade = "F" print("Grade:", grade)

This type of structure is useful when there are several possible outcomes.

4.12 Order of Conditions Matters

The order of conditions can affect the result.

Consider:

marks = 95 if marks >= 40:    print("Pass") elif marks >= 90:    print("Excellent")

The first condition is already true, so "Pass" is printed.

The better order is:

marks = 95 if marks >= 90:    print("Excellent") elif marks >= 40:    print("Pass")

Output:

Excellent

When conditions overlap, place the more specific or higher-priority condition first.

4.13 Nested if Statements

An if statement can be placed inside another if statement.

This is called a nested conditional statement.

Example:

age = 20 has_id = True if age >= 18:    if has_id:        print("Entry allowed")

The inner condition is checked only after the outer condition is true.

4.14 Nested if...else

Example:

username_correct = True password_correct = False if username_correct:    if password_correct:        print("Login successful")    else:        print("Incorrect password") else:    print("Incorrect username")

This structure can be useful when one decision depends on another.

However, deeply nested conditions can make programs difficult to read. Logical operators can sometimes make the code simpler.

4.15 Combining Conditions with and

Multiple conditions can be combined using and.

Example:

age = 25 has_ticket = True if age >= 18 and has_ticket:    print("Entry allowed") else:    print("Entry denied")

Both conditions must be true for the if block to execute.

4.16 Combining Conditions with or

The or operator can be used when either condition is sufficient.

Example:

is_student = False is_teacher = True if is_student or is_teacher:    print("Education member") else:    print("Not eligible")

At least one condition must be true.

4.17 Using not

The not operator reverses a Boolean condition.

Example:

is_locked = False if not is_locked:    print("Account is available")

Output:

Account is available

4.18 Comparing Strings

Conditional statements can also compare text.

Example:

password = input("Enter password: ") if password == "python123":    print("Access granted") else:    print("Access denied")

For real applications, passwords should not be stored as plain text. This example is only for learning conditional logic.

4.19 Case-Sensitive String Comparison

Python string comparisons are case-sensitive.

For example:

name = "Python" if name == "python":    print("Matched") else:    print("Not matched")

Output:

Not matched

"Python" and "python" are different strings.

You can normalize user input when appropriate:

answer = input("Continue? ").lower() if answer == "yes":    print("Continuing...")

4.20 Checking Membership

The in operator can be used in conditions.

Example:

fruit = "apple" if fruit in ["apple", "banana", "mango"]:    print("Fruit found") else:    print("Fruit not found")

This is useful when checking whether a value exists in a collection.

4.21 Conditional Expression

Python also supports a compact conditional expression.

Syntax:

value_if_true if condition else value_if_false

Example:

age = 20 status = "Adult" if age >= 18 else "Minor" print(status)

Output:

Adult

This style is useful for short and simple conditions.

For complicated logic, a normal if...else statement is usually easier to read.

4.22 Truthy and Falsy Values

Python conditions do not always have to contain an explicit comparison.

For example:

name = "Aman" if name:    print("Name is available")

A non-empty string is considered truthy.

An empty string is considered falsy:

name = "" if name:    print("Name is available") else:    print("Name is empty")

Output:

Name is empty

Similarly, values such as 0, False, None, and empty collections are commonly treated as false in conditions.

4.23 Example: Simple Login System

The following example demonstrates multiple conditions.

username = input("Enter username: ") password = input("Enter password: ") if username == "admin" and password == "python123":    print("Login successful") else:    print("Invalid username or password")

This is only a learning example and should not be used as a real authentication system.

4.24 Example: Temperature Classification

temperature = float(input("Enter temperature: ")) if temperature >= 35:    print("Very hot") elif temperature >= 25:    print("Warm") elif temperature >= 15:    print("Moderate") else:    print("Cool")

The program evaluates the ranges from top to bottom.

4.25 Example: Student Grade Program

marks = float(input("Enter marks: ")) if marks < 0 or marks > 100:    print("Invalid marks") elif marks >= 90:    print("Grade: A+") elif marks >= 80:    print("Grade: A") elif marks >= 70:    print("Grade: B") elif marks >= 60:    print("Grade: C") elif marks >= 40:    print("Grade: D") else:    print("Grade: F")

This example also demonstrates input validation.

4.26 Example: Largest of Two Numbers

a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) if a > b:    print("First number is larger") elif b > a:    print("Second number is larger") else:    print("Both numbers are equal")

4.27 Example: Largest of Three Numbers

a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) c = float(input("Enter third number: ")) if a >= b and a >= c:    print("First number is largest") elif b >= a and b >= c:    print("Second number is largest") else:    print("Third number is largest")

4.28 Common Mistakes

Mistake 1: Forgetting the colon

Incorrect:

if age >= 18    print("Adult")

Correct:

if age >= 18:    print("Adult")

Mistake 2: Incorrect indentation

Incorrect:

if age >= 18: print("Adult")

Correct:

if age >= 18:    print("Adult")

Mistake 3: Using = instead of ==

Incorrect:

if age = 18:    print("Age is 18")

Correct:

if age == 18:    print("Age is 18")

Mistake 4: Incorrect condition order

When using ranges, arrange conditions carefully.

For example:

if marks >= 40:    print("Pass") elif marks >= 90:    print("Excellent")

The elif will never be reached for marks of 90 or above because the first condition is already true.

A better arrangement is:

if marks >= 90:    print("Excellent") elif marks >= 40:    print("Pass") else:    print("Fail")

4.29 Mini Project: Student Result System

Let's create a small student result program.

name = input("Enter student name: ") maths = float(input("Enter Maths marks: ")) science = float(input("Enter Science marks: ")) english = float(input("Enter English marks: ")) total = maths + science + english average = total / 3 print("\nStudent:", name) print("Total:", total) print("Average:", average) if maths < 0 or maths > 100 or science < 0 or science > 100 or english < 0 or english > 100:    print("Invalid marks entered.") elif average >= 90:    print("Grade: A+") elif average >= 80:    print("Grade: A") elif average >= 70:    print("Grade: B") elif average >= 60:    print("Grade: C") elif average >= 40:    print("Grade: D") else:    print("Grade: F")

This project combines:

Variables

User input

Arithmetic operations

Comparison operators

Logical operators

if

elif

else

4.30 Chapter Summary

In this chapter, you learned:

What conditional statements are

The if statement

The if...else statement

The elif statement

Multiple elif conditions

Nested if statements

Logical operators with conditions

String comparisons

Membership conditions

Conditional expressions

Truthy and falsy values

Input validation

Common conditional-statement errors

Conditional statements allow Python programs to make decisions and respond differently to different situations.

Quick Revision Questions

1. What is the purpose of an if statement?
It executes a block of code when a specified condition is true.

2. What does else do?
It executes when the preceding if condition is false.

3. What does elif mean?
It means "else if" and allows another condition to be tested.

4. Can a Python program contain multiple elif statements?
Yes.

5. Can an if statement be placed inside another if statement?
Yes. This is called a nested if.

6. Why is indentation important in Python?
Indentation defines the blocks of code belonging to statements such as if, elif, and else.

7. Which operator checks equality?
==

8. Which operators can combine conditions?
and, or, and not.

9. What happens when none of the if or elif conditions is true and there is an else block?
The else block executes.

10. Can conditions compare strings?
Yes. Python allows string comparisons using operators such as ==, !=, <, and >.

Practice Exercises

Exercise 1: Voting Eligibility

Write a program that asks for a person's age and displays whether they are eligible to vote based on an age requirement of 18 years.

Exercise 2: Number Classification

Ask the user for a number and determine whether it is:

Positive

Negative

Zero

Exercise 3: Grade Calculator

Accept marks from the user and display an appropriate grade using if, elif, and else.

Exercise 4: Largest Number

Accept three numbers and determine the largest number.

Exercise 5: Login Check

Create a simple educational program that asks for a username and a predefined test password and displays whether the credentials match.

Exercise 6: Temperature

Ask the user for a temperature and classify it into suitable ranges such as cold, moderate, warm, or hot.

Chapter Activity

Create a Simple ATM Menu Program.

The program should:

Ask the user for an account balance.

Display options such as:

Check Balance

Deposit

Withdraw

Use conditional statements to perform the selected operation.

Prevent withdrawal when the requested amount is greater than the available balance.

Display the updated balance.

Try to use if, elif, else, comparison operators, and arithmetic operators.

Next Chapter: Python Loops – for and while