๐งญ Conditional Statements in Python#
Conditional statements make your program decide what to do based on different situations. They let your code be smart and choose a path depending on conditionsโlike a traffic light for your programโs flow! ๐ฆ
What Are Conditional Statements? ๐ค#
They allow you to execute certain blocks of code only if a specific condition is true.
1. The if
Statement โ
#
Basic way to run code when a condition is true.
age = 18
if age >= 18:
print("You are an adult.")
- The code inside the
if
block runs only ifage >= 18
is true.
2. The if-else
Statement ๐#
Choose between two paths.
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
3. The if-elif-else
Ladder ๐ช#
Check multiple conditions one by one.
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")
Important Tips for Conditionals#
- Conditions return True or False.
- Indentation after
if
,elif
, andelse
is mandatory. - Use comparison operators (
==
,!=
,<
,>
,<=
,>=
) in conditions.
Practice Questions with Solutions ๐#
- Practice: Write a program to check if a number is positive or negative.
- Solution:
num = int(input("Enter a number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
- Practice: Check if a person is eligible to vote (age 18 or more).
- Solution:
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote!")
else:
print("Not eligible yet.")
Step-by-Step Challenge: Simple Calculator ๐งฎ#
Write a program that asks the user to enter two numbers and an operator (+, -, *, /) and then performs the operation.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
if num2 != 0:
print(num1 / num2)
else:
print("Error! Division by zero.")
else:
print("Invalid operator.")
Checklist for This Chapter โ #
- Used
if
for simple decisions - Used
if-else
for two outcomes - Used
if-elif-else
for multiple choices - Handled conditions with comparison operators
Youโre now ready to control the flow of your programs using decisions! Start building smart, interactive apps! ๐ฆ๐