Conditional statements allow us to make decisions in our programs based on certain conditions. In Python, we use the if-else
statement to execute different blocks of code depending on whether a condition is true or false.
Let's learn how to use conditional statements in Python:
# Example 1: Checking if a number is positive or negative
num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is negative.")
# Example 2: Checking if a number is even or odd
num = 7
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
- In example 1, we check if the variable
num
is greater than 0. If it is, we print "The number is positive." Otherwise, we print "The number is negative." - In example 2, we use the modulo operator
%
to check if the variablenum
is divisible by 2. If the remainder is 0, it means the number is even. Otherwise, it is odd.
Now it's time for a practical task:
Write a Python program that prompts the user to enter their age. If the age is greater than or equal to 18, print "You are eligible to vote." Otherwise, print "You are not eligible to vote."
Spoiler warning
age = input("How old are you? ")
if int(age) >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Once you've completed the task, you can proceed to the next lesson.