Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

🔍

Python Conditional Statements



In real life, we make decisions all the time:

Python also lets us make decisions in our code using conditional statements.

What are Conditional Statements?

They let your program choose what to do depending on certain conditions.

In Python, we use:

1. The if Statement

This runs a block of code only if a condition is true.

x = 10

if x > 5:
    print("x is greater than 5")

Output:

x is greater than 5

Why? Because x is 10, and 10 is greater than 5.

2. The if-else Statement

This adds an "otherwise" case when the condition is false.

age = 16

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

Output:

You cannot vote.

Why? Because 16 is less than 18, so the else block runs.

3. The if-elif-else Ladder

Use elif when you have more than two choices.

marks = 75

if marks >= 90:
    print("Grade: A")
elif marks >= 70:
    print("Grade: B")
elif marks >= 50:
    print("Grade: C")
else:
    print("Grade: F")

Output:

Grade: B

Why? 75 is not >= 90, but it is >= 70, so the second block runs.

4. Nested if Statements

You can also put one if inside another. This is called nesting.

num = 10

if num > 0:
    if num % 2 == 0:
        print("Positive even number")

Output:

Positive even number

Why? First, num > 0 is true. Then, 10 % 2 == 0 (means even), so the inner print runs.

Important Notes

Try It Yourself

Change the values in the examples and see how the output changes. Try your own conditions too!

Conclusion

Conditional statements help your programs make decisions, just like you do in real life. Mastering these will let you build smarter and more interactive Python programs.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M