Python Interactive Guide - Step 2 Control Flow (2) - Conditional Statements (2): Conditional Expressions, Ternary Operator
- This course, Python Interactive Guide, is designed to help you learn the basics of Python programming through hands-on, interactive examples.
- The “Style Guide” sections introduce clean coding practices, mainly based on PEP8.
- You can run and experiment with every code example.
Feel free to try things out - reloading the page will reset everything.
This is a continuation of “Step 2 Control Flow”.
2.1. Conditional Statements
2.1.5. Conditional Expressions
An expression that evaluates to a bool value (True, False) is called a conditional expression.
In this section, we will look at various conditional expressions.
Comparison Operators
Symbols that compare two values, such as <= (greater than or equal to), are called comparison operators.
Using comparison operators, you can create conditional expressions like x <= 10.
Comparing Order
There are 4 types of operators for comparing the order of two values: >, <, >=, <=.
| Comparison operator | Meaning |
|---|---|
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
You can also chain multiple comparisons together as shown below.
Comparing Equality
There are 2 types of operators for comparing if two values are equal: ==, !=.
| Comparison operator | Meaning |
|---|---|
== |
Equal values |
!= |
Not equal values |
== (double equal sign).Be careful not to confuse it with
= (single equal sign) used for assignment.Comparing Identity
In the list example above, x and y are equal in value, but they are different objects.
You can check the object’s ID (unique identifier) using the id function.
As shown above, “being equal in value” and “being equal as objects” are different concepts.
To compare if two variables reference the same object, use the operators is and is not.
| Comparison operator | Meaning |
|---|---|
is |
Same object identity |
is not |
Different object identity |
Comparison with is and is not is faster than with == and !=,
so is and is not are used for comparing with unique objects like None.
In general, use them as follows:
- Comparing with
None:is,is not True,False: Use directly as a conditional expression (comparison operators usually unnecessary)- Comparing with other values:
==,!=
Membership Comparison
To check if one value is contained in another, use the operators in and not in.
| Comparison operator | Meaning |
|---|---|
in |
Contains |
not in |
Does not contain |
Logical Operators
Conditional expressions can be combined using logical operators.
| Logical operator | Meaning |
|---|---|
and |
Returns True only if both conditions are True |
or |
Returns True if either condition is True |
not |
Inverts the truth value of the condition |
When combining multiple conditions, it’s more readable to use parentheses () to clarify the order of evaluation.
The order of evaluation for logical operators is as follows:
notis evaluated first- Then
andis evaluated - Finally
oris evaluated
The logical operators and and or perform “short-circuit evaluation”.
- For
and: If the first expression isFalse, the result is definitelyFalse, so subsequent expressions are not evaluated - For
or: If the first expression isTrue, the result is definitelyTrue, so subsequent expressions are not evaluated
This is an important characteristic for efficient evaluation, but you need to be careful if you expect side effects (like function calls) in your expressions.
Create a program that meets the following conditions:
- Set variable
usernameto the string “admin” - Set variable
passwordto the string “secret123” - Set variable
attemptsto the number 3
Check the following conditions and output the result:
- If the username is “admin” and the password is “secret123”: “Login successful”
- If the username is “guest”: “Logged in as guest”
- If the number of attempts is 5 or more: “Account locked”
- Otherwise: “Login failed”
Example Solution
Type Checking (isinstance Function)
The isinstance function allows you to check if a value is of a specific type.
| Type Check | Description |
|---|---|
isinstance(value, type) |
Determines if the value is of the specified type |
You can also specify multiple types using a tuple:
Create a program that validates age as follows:
- Set a value to the variable
age - If
agemeets the following conditions, output “You areageyears old”- Conditions for
age:- It must be an integer
- It must be between
0and130inclusive
- Conditions for
- If the conditions are not met, output “Invalid input”
Example Solution
2.1.6. Ternary Operator
Value assignment using conditional statements can be written in one line using the ternary operator (conditional operator).
- The syntax of the ternary operator is as follows:
<value1> if <condition> else <value2>- If the condition is
True, the result is value1; ifFalse, the result is value2 - It makes code concise, but may reduce readability with complex conditions
- If the condition is
Rewrite the following program using a ternary operator.
Example Solution
2.1.7. Values Evaluated as Conditions
In conditional statements, condition expressions are evaluated as bool type True or False.
If a non-bool value is specified as a condition expression, it is evaluated as the bool value after applying the bool function.
- Values that are evaluated as
Falseinclude:False- Boolean FalseNone- None object0- Integer 00.0- Floating point 0""- Empty string[]- Empty list()- Empty tuple{}- Empty dictionaryset()- Empty set
- All other values are evaluated as
True.
Using this feature, you can concisely write value existence checks with logical operators:
- Conditional statements are expressed using
if,elif, andelse - Condition expressions use comparison operators (
>,<,>=,<=,==,!=,is,is not,in,not in) - Multiple conditions can be combined with logical operators (
and,or,not) - The
isinstancefunction can be used to check the type of a value. - Simple conditional statements can be expressed with the ternary operator (
<value1> if <condition> else <value2>) - Various values in Python are evaluated as boolean values
Create a shipping cost calculator for an online shopping site.
Create a program to calculate shipping costs according to the following specifications:
Basic Shipping Rules:
- Purchase amount
$50or more: Free shipping - Purchase amount from
$30to less than$50:$3shipping fee - Purchase amount less than
$30:$5shipping fee
Special Conditions:
- Premium members always get free shipping regardless of conditions below
- For products in the “Books” category: Flat shipping fee of
$2 - For shipping to “Alaska” or “Hawaii”: Additional
$5on top of the above shipping fee
Variables:
purchase_amount: Purchase amountis_premium: Whether the customer is a premium member (True/False)category: Product category (“Books”, “Electronics”, “Clothing”, etc.)destination: Shipping destination (“New York”, “California”, “Alaska”, “Hawaii”, etc.)
Finally, output in the format Purchase amount: $xx, Shipping fee: $xx, Total: $xx.
Challenge Elements:
- Test with different combinations of values
- Consider using ternary operators to write some processes concisely
- Use the
inoperator to efficiently check for special regions
Example Solution
Next time, we will continue with control flow by learning about “Loops”.