Contents

Python Quick Guide - Step 2 Control Flow (2) - Conditional Statements (2)

Info
  • 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”.

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.

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.

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.

There are 2 types of operators for comparing if two values are equal: ==, !=.

Comparison operator Meaning
== Equal values
!= Not equal values
Equal Operator
The operator to compare if “values are equal” is == (double equal sign).
Be careful not to confuse it with = (single equal sign) used for assignment.

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
Style Guide

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: ==, !=

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
📚Exercise

Create a program that meets the following conditions:

  1. Set variable username to the string “admin”
  2. Set variable password to the string “secret123”
  3. 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

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:

  1. not is evaluated first
  2. Then and is evaluated
  3. Finally or is evaluated
Column: Short-circuit Evaluation

The logical operators and and or perform “short-circuit evaluation”.

  • For and: If the first expression is False, the result is definitely False, so subsequent expressions are not evaluated
  • For or: If the first expression is True, the result is definitely True, 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.

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; if False, the result is value2
    • It makes code concise, but may reduce readability with complex conditions
📚Exercise

Rewrite the following program using a ternary operator.

Example Solution

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 False
    • None - None object
    • 0 - Integer 0
    • 0.0 - Floating point 0
    • "" - Empty string
    • [] - Empty list
    • () - Empty tuple
    • {} - Empty dictionary
    • set() - Empty set
  • All other values are evaluated as True.

Using this feature, you can concisely write value existence checks with logical operators:

Summary So Far
  • Conditional statements are expressed using if, elif, and else
  • 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
📚Comprehensive Exercise: Shopping Site Shipping Cost Calculator

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 amount
  • is_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:

  1. Test with different combinations of values
  2. Consider using ternary operators to write some processes concisely
  3. Use the in operator to efficiently check for special regions
Example Solution

Next time, we will continue with control flow by learning about “Loops”.

Related Content