Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn How to Combine Conditions 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 Combine Conditions in Python

In Boolean logic, two fundamental operators are OR and AND. The OR operator returns True if at least one of the conditions is true; otherwise, it returns False. The AND operator returns True only if both conditions are true; otherwise, it returns False. You can combine conditions using the and and or operators (always in lowercase)

  • condition1 and condition2 yields True only when both conditions are True;
  • condition1 or condition2 gives True if at least one condition is True.

Note

You can also chain multiple conditions using these operators. Use parentheses to make the order of operations clear.

For example, consider the following conditions:

  1. Whether 2 is greater than 1 and "bbb" is different from "aaa".
  2. Whether the character at index 2 in the string "my string" is either "y" or "s".
12345
# Check the first two conditions print(2 > 1 and 'bbb' != 'aaa') # Check the next two conditions print('my string'[2] == 'y' or 'my string'[2] == 's')
copy

The first print() returns True since both 2 > 1 and 'bbb' != 'aaa' are true. The second print() outputs False because the character at index 2 is neither 'y' nor 's' (it's actually a space).

Note

To reverse a boolean value, use the not operator. For example, not 1 == 1 results in False because 1 == 1 is True, and not negates it to False..

question mark

What output does the subsequent code produce?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

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