Python If Statements Explained with Examples
Learn how to use if statements in Python to make decisions in your code with easy examples and explanations.
In Python, an if statement allows your program to make decisions by executing certain code only if a condition is true. This helps your programs behave differently based on different inputs or situations.
The basic syntax of an if statement in Python is simple: you write the keyword 'if', followed by a condition, then a colon, and then the indented code block that runs if the condition is true. If the condition is false, the code block is skipped.
age = 18
if age >= 18:
print("You are an adult.")In this example, the program checks if the variable 'age' is greater than or equal to 18. Since age is 18, the condition is true, so it prints 'You are an adult.'. Indentation is important in Python here to show which code belongs to the if statement.
Common errors with if statements include forgetting the colon ':' at the end of the if line or incorrect indentation. For example, writing `if age >= 18` without ':' will cause a SyntaxError. This error means Python expected a colon to signify the start of the block. To fix it, just add the colon.
if age >= 18 # Missing colon here
print("You are an adult.")Remember to always add the colon `:` after the condition and indent the following block of code consistently to avoid errors.
You can also add an else statement to run code when the if condition is false:
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult yet.")In this case, since age is 16, the else block runs, printing "You are not an adult yet.". This way, your program can handle both possibilities clearly.
In summary, if statements in Python help your program decide what to do by checking conditions. Always remember the colon and indentation rules, and use else when you want to specify code for when the condition is false.