Python Quick Guide - Step 2 Control Flow (2) - Conditional Statements (2)
- This course is designed to help you learn the basics of Python programming as quickly as possible through hands-on practice.
- The “Style Guide” sections primarily cover guidelines from PEP8 for writing clean Python code.
- You can run and see the results of each code example.
Feel free to experiment with the code - reloading the page will reset the content.
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 |
Create a program that meets the following conditions:
- Set variable
username
to the string “admin” - Set variable
password
to the string “secret123” - Set variable
attempts
to 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
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:
not
is evaluated first- Then
and
is evaluated - Finally
or
is 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.
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
False
include: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
) - 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
$50
or more: Free shipping - Purchase amount from
$30
to less than$50
:$3
shipping fee - Purchase amount less than
$30
:$5
shipping 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
$5
on 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
in
operator to efficiently check for special regions
Example Solution
Next time, we will continue with control flow by learning about “Loops”.