Comparison Operators

Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater Than
<= Less than or Equal to
>= Greater than or Equal to

These operators evaluate to True or False depending on the values you give them.

Examples:

>>> 42 == 42
True

>>> 40 == 42
False

>>> 'hello' == 'hello'
True

>>> 'hello' == 'Hello'
False

>>> 'dog' != 'cat'
True

>>> 42 == 42.0
True

>>> 42 == '42'
False

Boolean (Logical) Operators

There are three Boolean operators: and, or, and not.

The and Operator’s Truth Table:

Expression Evaluates to
True and True True
True and False False
False and True False
False and False False

The or Operator’s Truth Table:

Expression Evaluates to
True or True True
True or False True
False or True True
False or False False

The not Operator’s Truth Table:

Expression Evaluates to
not True False
not False True

Mixing Operators

You can mix boolean and comparison operators:

>>> (4 < 5) and (5 < 6)
True

>>> (4 < 5) and (9 < 6)
False

>>> (1 == 2) or (2 == 2)
True

Also, you can mix use multiple Boolean operators in an expression, along with the comparison operators:

>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True

if Statements

The if statement evaluates an expression, and if that expression is True, it then executes the following indented code:

>>> name = 'Debora'

>>> if name == 'Debora':
...    print('Hi, Debora')
...
# Hi, Debora

>>> if name != 'George':
...    print('You are not George')
...
# You are not George

The else statement executes only if the evaluation of the if and all the elif expressions are False:

>>> name = 'Debora'

>>> if name == 'George':
...    print('Hi, George.')
... else:
...    print('You are not George')
...
# You are not George

Only after the if statement expression is False, the elif statement is evaluated and executed:

>>> name = 'George'

>>> if name == 'Debora':
...    print('Hi Debora!')
... elif name == 'George':
...    print('Hi George!')
...
# Hi George!

the elif and else parts are optional.

>>> name = 'Antony'

>>> if name == 'Debora':
...    print('Hi Debora!')
... elif name == 'George':
...    print('Hi George!')
... else:
...    print('Who are you?')
...
# Who are you?

Ternary Conditional Operator

Many programming languages have a ternary operator, which define a conditional expression. The most common usage is to make a terse, simple conditional assignment statement. In other words, it offers one-line code to evaluate the first expression if the condition is true, and otherwise it evaluates the second expression.

<expression1> if <condition> else <expression2>

Example:

>>> age = 15

>>> # this if statement:
>>> if age < 18:
...    print('kid')
... else:
...    print('adult')
...
# output: kid

>>> # is equivalent to this ternary operator:
>>> print('kid' if age < 18 else 'adult')
# output: kid

Ternary operators can be chained:

>>> age = 15

>>> # this ternary operator:
>>> print('kid' if age < 13 else 'teen' if age < 18 else 'adult')

>>> # is equivalent to this if statement:
>>> if age < 18:
...     if age < 13:
...         print('kid')
...     else:
...         print('teen')
... else:
...     print('adult')
...
# output: teen

:bulb: Note that Python introduce match statement as another control statement in Python 3.10 to implement switch statement

while Loop Statements

The while statement is used for repeated execution as long as an expression is True:

>>> spam = 0
>>> while spam < 5:
...     print('Hello, world.')
...     spam = spam + 1
...
# Hello, world.
# Hello, world.
# Hello, world.
# Hello, world.
# Hello, world.

break Statements

If the execution reaches a break statement, it immediately exits the while loop’s clause:

>>> while True:
...     name = input('Please type your name: ')
...     if name == 'your name':
...         break
...
>>> print('Thank you!')
# Please type your name: your name
# Thank you!

It also works for the for loop

>>> for i in range(5):
...     if i == 3:
...         break
...     print(i)
# 0
# 1
# 2

continue Statements

When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop.

>>> while True:
...     name = input('Who are you? ')
...     if name != 'Joe':
...         continue
...     password = input('Password? (It is a fish.): ')
...     if password == 'swordfish':
...         break
...
>>> print('Access granted.')
# Who are you? Charles
# Who are you? Debora
# Who are you? Joe
# Password? (It is a fish.): swordfish
# Access granted.

It also works for the For loop

>>> for i in range(5):
...     if i == 3:
...         continue
...     print(i)
# 0
# 1
# 2
# 4

For loop

The for loop iterates over an iterable object like range(), list, tuple, dictionary, set or string:

>>> pets = ['Bella', 'Milo', 'Loki']
>>> for pet in pets:
...     print(pet)
...
# Bella
# Milo
# Loki

The range() function

The range() function returns a sequence of numbers. It starts from 0, increments by 1, and stops before a specified number:

>>> for i in range(5):
...     print('Will stop at 5! or 4 ?'+str(i))
...
# Will stop at 5! or 4? 0
# Will stop at 5! or 4? 1
# Will stop at 5! or 4? 2
# Will stop at 5! or 4? 3
# Will stop at 5! or 4? 4

The range() function can also modify it's 3 defaults arguments. The first two will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration.

# range(start, stop, step)
>>> for i in range(0, 10, 2):
...    print(i)
...
# 0
# 2
# 4
# 6
# 8

You can even use a negative number for the step argument to make the for loop count down instead of up.

>>> for i in range(5, -1, -1):
...     print(i)
...
# 5
# 4
# 3
# 2
# 1
# 0

Ending a Program with sys.exit()

exit() function allows exiting Python.

>>> import sys

>>> while True:
...     feedback = input('Type exit to exit: ')
...     if feedback == 'exit':
...         print('You typed '+ feedback)
...         sys.exit()
...
# Type exit to exit: open
# Type exit to exit: close
# Type exit to exit: exit
# You typed exit

The random module

seed()

The seed method is used to initialize the random number generator.

>>> random.seed(1)
>>> random.random()
# 0.13436424411240122

Setting the seed to a number will always return the same random number:

>>> random.seed(1)
>>> random.random()
# 0.13436424411240122

>>> random.seed(1)
>>> random.random()
# 0.13436424411240122

>>> random.seed(1)
>>> random.random()
# 0.13436424411240122

>>> random.seed(1)
>>> random.random()
# 0.13436424411240122

>>> random.seed(1)
>>> random.random()
# 0.13436424411240122

randint()

random.randint(start: int, stop: int)

This method returns a random number between a given start and stop parameters:

>>> random.randint(1, 5)
# 3
>>> random.randint(1, 5)
# 2
>>> random.randint(1, 5)
# 5
>>> random.randint(1, 5)
# 1
>>> random.randint(1, 5)
# 3
>>> random.randint(1, 5)
# 1

shuffle()

The shuffle method takes in an iterable and shuffle it:

>>> my_list = [1, 2, 3, 4]

>>> random.shuffle(my_list)
>>> my_list
# [1, 4, 3, 2]

>>> random.shuffle(my_list)
>>> my_list
# [2, 4, 3, 1]

>>> random.shuffle(my_list)
>>> my_list
# [4, 2, 3, 1]

Keywords

  • Flow control statements (流程控制語句): Instructions that determine the order in which code is executed.
  • boolean expression (布林運算式): An expression that evaluates to either True or False.
  • Boolean values (布林值): The two truth values in Python: True and False.
  • comparison operators (比較運算子): Operators like ==, !=, <, >, <=, and >= that compare values.
  • Boolean operators (布林運算子): Operators such as and, or, and not used to combine or invert boolean expressions.
  • sequential execution (循序執行): The process where code runs one statement after the other in order.
  • selection statement (選擇敘述): A statement that lets the program choose between different paths based on conditions (e.g., if statements).
  • repetition statement (重複敘述): A loop that repeats a block of code until a condition is met (e.g., for or while loops).
  • structured programming (結構化程式設計): A style of programming that uses blocks, loops, and functions to create clear, logical code.
  • condition (條件): A boolean expression used to decide which code path to take.
  • clause (子句): A part of a control structure, such as the condition part of an if-statement.
  • block of code (程式區塊): A group of statements that are executed together, usually defined by indentation.
  • indentation (縮排): Spaces at the beginning of a line that define blocks of code in Python.
  • control structures (控制結構): Constructs like loops and conditional statements that control the flow of execution.
  • if-statement (if 敘述 ): A conditional statement that executes code only if a specified condition is True.
  • ternary conditional operator (三元條件運算子): A compact way to write an if-else statement that returns one of two values based on a condition.
  • while statement (while 敘述): A loop that repeats a block of code as long as a condition remains True.
  • Augmented assignments (增量賦值): Shorthand operators (like +=, -=, *=) that update a variable's value in place.
  • break statement (break 敘述): A command that immediately exits a loop.
  • infinite loop (無限迴圈 ): A loop that never stops running on its own unless interrupted.
  • continue statement (continue 敘述): A command that skips the rest of the current loop iteration and moves to the next one.
  • for loop statement (for 迴圈敘述): A loop that iterates over each item in a sequence, executing a block of code for each item.
  • in (in 關鍵字): A keyword used to check if a value exists in a sequence or to iterate over items in that sequence.
  • sequence type (序列型態): Data types that store ordered collections of items, such as lists, tuples, and strings.
  • standard library (標準函式庫): A collection of modules and functions that come with Python to help perform many common tasks.