Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Combining Conditions | Conditional Statements
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

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

book
Combining Conditions

In Boolean logic, two fundamental operators are OR and AND. What do they represent?

The OR operator checks if either of the conditions is true and returns True if so; otherwise, it returns False.

The AND operator ensures both conditions are true before returning True. If not, it returns False. In Python, to combine conditions, use the and & or operators (always in lowercase).

For example:

  • 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 more than two conditions using these operators. Employ parentheses to clarify the order of operations.

As an illustration, consider these conditions:

  1. Whether 2 exceeds 1 and if "bbb" isn't the same as "aaa";
  2. If the character with index 2 in the string "my string" is either "y" or "s".
1234
# 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

How should we interpret the outcomes? The initial print() issues a True response since both 2 > 1 and "bbb" != "aaa" hold true. The following print() yields False because the character at index 2 is neither 'y' nor 's' (it's actually a space).

Note

If you wish to reverse a boolean value, employ the not operator. For instance, not 1 == 1 results in False because 1 == 1 is True, and we've negated that to False.

What output does the subsequent code produce?

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