Python If Else Statement

🐍 Python If Statement

The if statement is used to control the flow of a program based on conditions.


🔹 1. Basic If Statement

age = 18

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

✅ Output:

You are an adult.

Note: Indentation is important in Python (usually 4 spaces).


🔹 2. If…Else Statement

When you want to execute one block if True, and another if False:

age = 16

if age >= 18:
print(“You are an adult.”)
else:
print(“You are a minor.”)


🔹 3. If…Elif…Else Statement

Use elif for multiple conditions:

marks = 75

if marks >= 90:
print(“Grade: A+”)
elif marks >= 75:
print(“Grade: A”)
elif marks >= 60:
print(“Grade: B”)
else:
print(“Grade: C”)


🔹 4. Nested If Statements

You can put if statements inside other if statements:

age = 20
gender = "Male"
if age >= 18:
if gender == “Male”:
print(“Adult Male”)
else:
print(“Adult Female”)
else:
print(“Minor”)


🔹 5. Logical Operators in Conditions

You can combine conditions using:

Operator Meaning
and Both conditions must be True
or At least one must be True
not Reverse the result

Example:

age = 20
citizen = True
if age >= 18 and citizen:
print(“You can vote!”)


🔹 6. Python Ternary Operator (Single Line If)

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

🔹 7. Membership Check with If

fruits = ["Apple", "Banana", "Mango"]

if “Apple” in fruits:
print(“Apple is available.”)


🔹 8. Boolean Condition Directly

Since Python treats True/False directly:

is_raining = True

if is_raining:
print(“Take an umbrella.”)


🔹 9. Comparison Operators Used in If

Operator Meaning
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal

Example:

x = 10
y = 5
if x > y:
print(“x is greater than y”)


🔹 10. Example Program: Age & Eligibility

age = int(input("Enter your age: "))
citizenship = input("Enter citizenship: ")
if age >= 18 and citizenship.lower() == “india”:
print(“You can vote!”)
elif age < 18:
print(“You are too young to vote.”)
else:
print(“You cannot vote due to citizenship.”)


🧠 Summary

  • if → executes code if condition is True

  • else → executes code if condition is False

  • elif → checks multiple conditions

  • Logical operators (and, or, not) help combine conditions

  • Ternary operator → shortcut for simple if-else


🔹 Practice Exercises

  1. Write a program to check if a number is positive, negative, or zero.

  2. Check if a student passes with marks >= 40, otherwise fail.

  3. Check if a year is a leap year.

  4. Check if a person is eligible to drive based on age >= 18.

  5. Use ternary operator to print “Even” or “Odd” for a number.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *