Adding else Statements

Code Examples

Example 1

Simple if-else Statement. Since 15 is not greater than or equal to 18, the if condition is False. Python skips the first print statement and executes the code in the else block instead, printing "You're too young to vote."

age = 15
if age >= 18:
    print("You can vote!")
else:
    print("You're too young to vote.") # This will print

Example 2

The strings don't match, so the condition is False. The else block executes, denying access. This pattern is common in security checks where you need to handle both success and failure.

password = "wrong123"
if password == "secret123":
    print("Access granted! Welcome!")
else:
    print("Access denied. Wrong password.") # This will print

Example 3

Since is_sunny is False, the if condition fails and the else block runs. This shows how else works with boolean variables to handle both true and false scenarios.

is_sunny = False
if is_sunny:
    print("Perfect day for a picnic!")
else:
    print("Maybe stay indoors today.") # This will print

Example 4

If the user types exactly "yes", the if block runs. Any other input (including "Yes", "no", or anything else) will trigger the else block. This shows how else catches all non-matching cases.

answer = input("Do you like pizza? (yes/no): ")
if answer == "yes":
    print("Great! Pizza is delicious!")
else:
    print("That's okay, everyone has different tastes.")

Example 5

Since 65 < 70, the condition is False. Python skips all three statements in the if block and executes all three statements in the else block. Both blocks can contain multiple indented statements.

score = 65
if score >= 70:
    print("Congratulations!")
    print("You passed the test!")
    print("Well done!")
else:
    print("Sorry, you didn't pass.")
    print("Your score was:", score)
    print("Study more and try again!")

Example 6

If the user enters any text, name will be truthy and the if block runs. If they just press Enter without typing anything, name will be an empty string (falsy), and the else block runs instead.

name = input("Enter your name: ")
if name:
    print("Hello,", name + "!")
else:
    print("You didn't enter a name.")