Monday, August 25, 2025

🐍CONDITIONAL STATEMENTS

Conditional Statements in Python

Learn how to make decisions in your programs using if, elif, and else.

Introduction

Conditional statements allow your program to perform different actions based on certain conditions. In Python, we use if, elif (else if), and else for decision-making.

Syntax Structure


if condition:
    # code to execute if condition is True
elif another_condition:
    # code to execute if another_condition is True
else:
    # code to execute if all above conditions are False

Example:


age = 18

if age >= 18:
    print("You can vote")
else:
    print("You cannot vote")

Common Mistakes and Errors

  • Case-Sensitivity: Python keywords must be lowercase. Writing If, Elif, or Else will throw an error.
    If age >= 18:
        print("You can vote")
    SyntaxError: invalid syntax
  • Missing colon at the end of if or elif:
    if age >= 18
        print("You can vote")
    SyntaxError: expected ':'
  • Wrong indentation:
    if age >= 18:
    print("You can vote")
    IndentationError: expected an indented block
    ✅ Correct:
    if age >= 18:
        print("You can vote")
  • Using assignment = instead of comparison ==:
    if age = 18:
        print("You are 18")
    SyntaxError: invalid syntax
  • Using elif without a previous if:
    elif age >= 18:
        print("You can vote")
    SyntaxError: invalid syntax

Nested Conditions

You can place an if or else inside another if to make complex decisions:


age = 20
citizen = True

if age >= 18:
    if citizen:
        print("You can vote")
    else:
        print("You are not a citizen")
else:
    print("You cannot vote")

💡 Try It Yourself

  1. Ask the user for their age and print whether they are a child, teenager, or adult using if-elif-else.
  2. Write a program to check if a number is positive, negative, or zero.
  3. Combine two conditions: ask for age and citizenship, print if they can vote or not (nested if).

What’s Next?

Now that you know basic conditionals, the next topic is Nested Conditions — learning how to handle multiple layers of decisions.

➡️ Next: More on Nested Conditions in Python

⬅️ Back to Main Page

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??