Welcome back to our Python journey! Today we're going to delve into a fundamental aspect of programming that will help you make your code more dynamic and versatile: If-Else Statements. These statements enable us to create conditional logic in our programs, allowing them to react differently depending on certain conditions. Let's see what you'll learn today:
An If-Else Statement is a control flow structure that lets your code execute different blocks of code based on whether a given condition is true or false. It's made up of three main parts: the if
, else
, and optional elif
statements. Here's a simple example:
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
In this case, the condition is age >= 18
. If it's true (i.e., age
is equal to or greater than 18), then the code inside the if
block will be executed (printing "You are an adult."). Otherwise, if the condition is false, the code inside the else
block will be executed (printing "You are not an adult.").
The keyword elif
allows you to create more complex conditions. For example:
age = 10
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
In this case, the code checks the conditions sequentially. First, it checks if age
is greater than or equal to 18 (adult). If that's not true, then it moves on to check if age
is greater than or equal to 13 (teenager). If neither of these conditions is met, it will execute the code inside the else
block (child).
Let's see how If-Else Statements can be used in real-world scenarios:
grade = int(input("Enter your grade (0-100): "))
if grade >= 90:
print("Your grade is A.")
elif grade >= 80:
print("Your grade is B.")
elif grade >= 70:
print("Your grade is C.")
elif grade >= 60:
print("Your grade is D.")
else:
print("Your grade is F.")
This code calculates a student's grade based on their score.
year = int(input("Enter a year (e.g., 2023): "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
This code determines whether a given year is a leap year.
What causes it: Incorrect indentation or syntax in the if-else structure.
if age >= 18:
print("You are an adult.")
else:print("You are not an adult.")
Error message:
File "example.py", line 2
else:print("You are not an adult.")
^
SyntaxError: invalid syntax
Solution: Ensure proper indentation for both the if
and else
blocks.
Why it happens: Indentation is crucial in Python as it indicates the grouping of statements.
How to prevent it: Always use consistent indentation and ensure that all lines inside an if or else block are properly indented.
What causes it: Attempting to use a variable that has not been defined yet.
print(age)
if age >= 18:
print("You are an adult.")
Error message:
Traceback (most recent call last):
File "example.py", line 1, in <module>
print(age)
NameError: name 'age' is not defined
Solution: Define the variable before using it in the if-else statement.
Why it happens: Python does not automatically create variables for you, so any variable used must be defined prior to use.
How to prevent it: Always declare your variables before using them in your code.
What causes it: Comparing different data types that cannot be compared directly (e.g., comparing a string with an integer).
if "10" > 5:
print("10 is greater than 5.")
Error message:
Traceback (most recent call last):
File "example.py", line 1, in <module>
if "10" > 5:
TypeError: unorderable types: str() > int()
Solution: Convert the data types to a common format before making the comparison (e.g., using int("10")
).
Why it happens: Different data types have different comparison rules, and not all can be compared directly.
How to prevent it: Be mindful of the data types you're working with and ensure they can be compared directly or convert them to a common format if necessary.
elif
statementsif-else
statements when possibleNow that you've learned about If-Else Statements, you can build more dynamic and versatile programs! As always, keep practicing and exploring new concepts. In our next lesson, we'll delve into loops, another essential aspect of programming in Python. Happy coding!