Introduction to Python
3. Conditional Statements
Introduction to Python
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
The AND operator ensures both conditions are true before returning
True. If not, it returns
In Python, to combine conditions, use the
or operators (always in lowercase). For example:
condition1 and condition2yields
Trueonly when both conditions are
condition1 or condition2gives
Trueif at least one condition is
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:
"bbb"isn't the same as
- If the character with index
2in the string
"my string"is either
2 > 1 and "bbb" != "aaa"involves two conditions connected by the
andoperator. The first condition
2 > 1is true because 2 is greater than 1. The second condition
"bbb" != "aaa"is also true because the strings "bbb" and "aaa" are not equal. Since both conditions are true and they are connected by
and, the entire expression evaluates to true.
In the second line,
"my string" == "y" or "my string" == "s"checks two conditions connected by the
oroperator. The expression
"my string"refers to the third character of the string "my string", which is " ". The first condition
"my string" == "y"is false. The second condition
"my string" == "s"is false, and since both of the conditions is false and they are connected by
or, the overall expression evaluates to false.
How should we interpret the outcomes? The initial
print() issues a
True response since both
2 > 1 and
"bbb" != "aaa" hold true. The following
False because the character at index
2 is neither
's' (it's actually a space).
If you wish to reverse a boolean value, employ the
notoperator. For instance,
not 1 == 1results in
1 == 1is
True, and we've negated that to
What output does the subsequent code produce?
Select the correct answer
print(0 > 10 and 5 > 2): This prints
5 > 2is true,
0 > 10is false. The
andoperator requires both conditions to be true, but since one is false, the overall expression is false.
print(2*2 == 5 or 1+1 != 3): This prints
2*2 == 5is false, but
1+1 != 3is true. The
oroperator only requires one of the conditions to be true for the overall expression to be true.
Everything was clear?