SwadhyAI Notes

All Python notes

Python If...Else 🔀

Making Decisions

Conditional statements allow your program to make decisions. Python supports the usual logical conditions from mathematics (equals, not equals, less than, etc.).

🚪 Analogy: The Club Bouncer

Think of an if statement as a bouncer at a club.
- If you are 18 or older, you can enter.
- Else, you have to go home.
The code inside the if block only runs if the condition is met.

✨ The if Statement

python
a = 33
b = 200
if b > a:
  print("b is greater than a")

Note: Python uses indentation (whitespace) to define the scope of the code. Without indentation, it will raise an error.

🎯 Real-World Application: Login System

Every login screen uses simple logic like this:

python
username = input("Username: ")
password = input("Password: ")

if username == "admin" and password == "secret123":
    print("Access Granted! Welcome, Admin.")
elif username == "guest":
    print("Welcome, Guest. You have limited access.")
else:
    print("Access Denied. Incorrect credentials.")

🔄 Elif and Else

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition". The else keyword catches anything which isn't caught by the preceding conditions.

python
score = 85

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

âš¡ Short Hand If...Else

If you have only one statement to execute, you can put it all on the same line. This is also known as the Ternary Operator.

python
a = 2
b = 330
print("A") if a > b else print("B")

# You can also use it for variable assignment
status = "Adult" if age >= 18 else "Minor"

🧠 Logical Operators

You can combine conditional statements using and, or, and not.

python
a = 200
b = 33
c = 500

if a > b and c > a:
  print("Both conditions are True")

if a > b or a > c:
  print("At least one of the conditions is True")

📦 Nested If

You can have if statements inside if statements, this is called nested if statements.

python
x = 41

if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")

✨ Pro Tip: Truthy Values

In Python, you don't always need to check if len(my_list) > 0. Empty lists, strings, and 0 are automatically "False".

python
my_list = ["apple", "banana"]

# Pythonic way to check if list is not empty
if my_list:
    print("List has items!")

💡 Did You Know? The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

python
if b > a:
  pass