Welcome!
Join our coding community
Ā© 2024 Ace Coding Academy
Code Examples
Example 1
Simple if Statement. This checks if the temperature is greater than 25. Since 30 > 25 is True, Python executes the indented code and prints "It's a hot day!". Notice the colon (:) after the condition and the indentation of the print statement.
temperature = 30
if temperature > 25:
print("It's a hot day!")
Example 2
if Statement with No Action. Here, since 15 is not greater than or equal to 18, the condition is False. Python skips the indented code completely, so nothing gets printed. The program continues running but no action is taken.
age = 15
if age >= 18:
print("You can vote!")
Example 3
Using Boolean Variables. When using a boolean variable directly, Python checks if it's True. Since is_raining is True, the message gets printed. This is a clean way to use boolean variables in conditions.
is_raining = True
if is_raining:
print("Don't forget your umbrella!")
Example 4
String Comparison. This compares two strings using the equality operator (==). Since both strings are identical, the condition is True and "Access granted!" is printed. Remember to use == for comparison, not = (which is for assignment).
password = "secret123"
if password == "secret123":
print("Access granted!")
Example 5
Multiple Statements in if Block. When the condition is True, Python executes ALL the indented statements inside the if block. All three print statements will run because they're all indented at the same level.
score = 85
if score >= 80:
print("Congratulations!")
print("You passed with a high grade!")
print("Keep up the good work!")
Example 6
Using Input with if Statement. This combines user input with an if statement. The program asks for a name, and only if the user types "Alice" exactly, it prints the welcome message. This shows how if statements can respond to user input.
name = input("What's your name? ")
if name == "Alice":
print("Hello Alice, welcome back!")
Example 7
Checking Empty Values. An empty string is considered False in Python. Since username is empty, the condition is False and nothing gets printed. This is useful for checking if variables have values.
username = ""
if username:
print("Welcome,", username)