Week 2: Mastering Variables, Data, and Operations
Unlocking the power to store and manipulate information in Python.
Dive into Chapter 2Arithmetic Operators: Performing Calculations.
Arithmetic operators are used to perform mathematical operations on numbers.
| Operator | Name | Example | Result | Description |
|---|---|---|---|---|
| `+` | Addition | `5 + 3` | `8` | Adds two operands. |
| `-` | Subtraction | `5 - 3` | `2` | Subtracts the second operand from the first. |
| `*` | Multiplication | `5 * 3` | `15` | Multiplies two operands. |
| `/` | Division | `5 / 3` | `1.666...` | Divides the first operand by the second (always results in a float). |
| `//` | Floor Division | `5 // 3` | `1` | Divides the first operand by the second, rounding down to the nearest whole number (integer). |
| `%` | Modulo | `5 % 3` | `2` | Returns the remainder of the division of the first operand by the second. |
| `**` | Exponentiation | `5 ** 3` | `125` | Raises the first operand to the power of the second. |
Let's see some examples in code:
a = 10
b = 4
print("a + b =", a + b) # Output: a + b = 14
print("a - b =", a - b) # Output: a - b = 6
print("a * b =", a * b) # Output: a * b = 40
print("a / b =", a / b) # Output: a / b = 2.5
print("a // b =", a // b) # Output: a // b = 2
print("a % b =", a % b) # Output: a % b = 2
print("a b =", a b) # Output: a ** b = 10000
Logical Operators: Combining Conditions.
Logical operators are used to combine or modify boolean values. Python has three main logical operators: `and`, `or`, and `not`.
- `and` (Logical AND): Returns `True` if both operands are `True`. Otherwise, it
returns `False`.
Operand 1 Operand 2 Result (Operand 1 and Operand 2) `True` `True` `True` `True` `False` `False` `False` `True` `False` `False` `False` `False` age = 25 has_license = True can_drive = age >= 18 and has_license print("Can drive:", can_drive) # Output: Can drive: True - `or` (Logical OR): Returns `True` if at least one of the operands is `True`. It
returns `False` only if both operands are `False`.
Operand 1 Operand 2 Result (Operand 1 or Operand 2) `True` `True` `True` `True` `False` `True` `False` `True` `True` `False` `False` `False` is_weekend = True is_holiday = False can_relax = is_weekend or is_holiday print("Can relax:", can_relax) # Output: Can relax: True - `not` (Logical NOT): Returns the opposite of the operand's boolean value. If
the operand is `True`, `not` returns `False`, and if the operand is `False`, `not` returns
`True`.
Operand Result (not Operand) `True` `False` `False` `True` is_raining = False is_sunny = not is_raining print("Is sunny:", is_sunny) # Output: Is sunny: True