- Setting a Variable:
# Set a variable
x = 10
Here, we’re creating a variable named x
and assigning it the value 10
.
- Using
if
,elif
, andelse
Statements:
# Check conditions using if, elif, and else
if x > 5:
# Code to execute if the condition is True
print("x is greater than 5")
elif x == 5:
# Code to execute if another_condition is True
print("x is equal to 5")
else:
# Code to execute if none of the above conditions are True
print("x is less than 5")
- The
if
statement checks ifx
is greater than 5. If it’s true, it executes the indented code block underif
. - The
elif
statement (short for “else if”) checks ifx
is equal to 5. If the previous condition (inif
) is not true, it checks this condition. If true, it executes the indented code block underelif
. - The
else
statement provides a code block that will be executed if none of the previous conditions are true.
- Executing the Code:
When you run this Python script, it will print “x is greater than 5” because the value ofx
(10) is indeed greater than 5. - Indentation:
In Python, indentation is crucial. The lines of code within theif
,elif
, andelse
blocks are indented to indicate that they are part of those blocks. Incorrect indentation can lead to syntax errors. - Logical Operators:
You can use logical operators (and
,or
,not
) to combine multiple conditions. For example:
age = 25
if age >= 18 and age <= 30:
print("You are between 18 and 30 years old")
This checks if age
is both greater than or equal to 18 and less than or equal to 30.
Remember, this is a basic example. As you become more familiar with Python, you’ll encounter more complex uses of if
statements and conditions. Practice and experimentation are key to mastering conditional statements in Python!
Image by Gerd Altmann from Pixabay