Course Content
Introduction to Python
Introduction to Python
How to Use if/else Expressions in Python
Now that conditional operators are understood, they can be used to branch code based on specific conditions. In Python, this is done using the following structure:
The condition
can be a conditional statement or a boolean value, such as a != 4
or b > 100
. The commands under if
and else
are executed based on whether the condition is met. These can include print()
statements, variable assignments, arithmetic operations, string manipulations, and more.
Now, let's go through an example: Suppose you have a string and want to check if it's long. A string is considered long if it contains more than 20
characters.
# Assign some variable test = "small string" # Conditional statement if len(test) > 20: print("This string is long!") else: print("Nothing special") # Check on different string test = "This string is very-very and very large" # Conditional statement if len(test) > 20: print("This string is long!") else: print("Nothing special")
Note
Remember, the code blocks under
if
andelse
must have consistent indentation (e.g., 2 spaces, 4 spaces, etc.).
Thanks for your feedback!