Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn How to Use if/else Expressions in Python | Conditional Statements in Python
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

1. First Acquaintance with Python
2. Variables and Types in Python
3. Conditional Statements in Python
4. Other Data Types in Python
5. Loops in Python
6. Functions in Python

book
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.

1234567891011121314151617
# 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")
copy

Note

Remember, the code blocks under if and else must have consistent indentation (e.g., 2 spaces, 4 spaces, etc.).

question mark

Given the provided if/else block, what will be the output if a = 95, and what if a = 56?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 6
We're sorry to hear that something went wrong. What happened?
some-alt