---
# System prepended metadata

title: 11-09 Expressions and Operators
tags: [Unit 2 - Expressions and Operators]

---

> Go and work\
> Honor the One who is working on you.\
> Do so by making beautiful things,\
> Be serving in beautiful ways,\
> By speaking up for the weak whose beauty is being maligned,\
> By filling this city with the aroma of good and beautiful work
>
> Reflect the beautiful work of your heavenly Father,\
> Nourished now by the grace and mercy of Christ,\
> In the power of the Holy Spirit.
>
> God has already accomplished the great work.\
> God goes before you and behind you.\
> God works at your side.
>
> (Matthew Kaemingk & Cory B. Willson, *Work and Worship*, p. 140)

# Arithmetic Operators

| Operation                       | Operator |  Example  | Evaluates to |
|---------------------------------|:--------:|:---------:|:------------:|
| Addition                        |   `+`    |  `2 + 2`  |     `4`      |
| Subtraction                     |   `-`    |  `4 - 1`  |     `3`      |
| Multiplication                  |   `*`    | `1.5 * 2` |    `3.0`     |
| Division                        |   `/`    |  `5 / 2`  |    `2.5`     |
| Floor Division                  |   `//`    |  `5 // 2`  |     `2`      |
| Modulus (remainder of division) |   `%`    |  `5 % 2`  |     `1`      |
| Exponent                        |   `**`   |  `3**3`   |     `27`     |

## Resulting types

-   If any of the operands is a float, result will be a float. Otherwise (both are integer), result is an integer.
-   However, there is an exception: result of a **division** (not floor division) is ***always*** a float. Careful with that! (why? we'll see in a moment)

## Using modulus (some exercises)

1. Ask the user to input a total number of seconds, then determine the equivalent hours, minutes, and remaining seconds.
&nbsp;
&nbsp;
&nbsp;

2. Ask the user to input a number, then check if the number is a multiple of 7.

&nbsp;
&nbsp;
&nbsp;

3. Ask the user to enter a day of the month (1-31), and give the day of week (Sunday, Monday, etc.). Suppose it is a 31-day month that starts on Monday.

&nbsp;
&nbsp;
&nbsp;

## Operator precedence

-   Always be careful with expressions using more than one operator! For example:

```python
a = 3
b = 6
c = a + b * 2
print(c)
```

-   This evaluates as $a + (b \times 2) = 3 + (6 * 2) = 3 + 12 = 15$

Python operator **precedence order**:

1.  Parentheses: `()`
2.  Exponents: `**`
3.  Multiplication, divisions and modulus: `* / // %`
4.  Addition and subtraction: `+ -`
5.  Comparisons: `<= < >= > == != is` (next week)
6.  Boolean `not` (next week)
7.  Boolean `and` (next week)
8.  Boolean `or` (next week)

## Operators in strings

-   Python also permits using SOME operators with strings. In a metaphorical way...

| String Operation | Metaphor       | Operator |         Example         | Evaluates to  |
|---------------|---------------|:-------------:|:-------------:|:-------------:|
| Concatenation    | Addition       |   `+`    | `"Hey" + " " + "apple"` | `"Hey apple"` |
| Repetition       | Multiplication |   `*`    |       `"na" * 4`        | `"nananana"`  |

-   Other operators are not supported. Multiplication of a string with another string is also not supported. Both wouldn't make so much sense...

## Evaluating operations in strings

It is also possible to evaluate an expression coded as a string. For example:

```python
expression = "2 * (4 + 6) / 3 - 5"
result = eval(expression)
print(result)
```

# Assignment Operators

When Python sees the operator `=`, it does the following:

1.  Evaluates the **right-hand side** (rhs)
    -   The right of the assignment operator can be:
        -   Objects: `age = 21`
        -   Variables: `my_cost = your_cost`
        -   Expressions: `x = (x + 1) * y`
2.  Assigns the resulting object to the variable on the **left-hand side** (lhs)
    -   Only a **single variable** is allowed on the left side!
    -   For example, `x + 1 = 2` is WRONG SYNTAX!

## Compound assignment operators

-   Python and other languages make available a shortcut for performing operations in variables and updating them.
-   For example,

```python
w = 5
w += 1
print(w)
```

is the same as:

```python
w = 5
w = w + 1
print(w)
```

You can use compound assignment with all operators!

```python
y += 1 # add then assign value
y -= 1 # subtract then assign value
y *= 2 # multiply then assign value
y /= 3 # divide then assign value
y // = 5 # floor divide then assign value
y **= 2 # increase to the power of then assign value
y %= 3 # return remainder then assign value
```

Example: what will this expression do?

```{python}
#| echo: true
#| eval: false
x *= y - 2
```

# Overflow

-   Integers and floats are representations in the memory of your computer. Therefore, there are **value limits to these numbers**.
    -   If we pass the limit, we have an **overflow**, and the number is not computed correctly.

-   **For integers**, Python dynamically increases the use of memory as the number grows. Therefore, **in theory** there is a limit (computer memory will be full), but **in practice** this will almost never be the case.
    - For example, try `2147483647 ** 200`
    - This, however, is a Python feature. Other languages may not handle that.

-   **For floats**, numbers are limited by the size of the mantissa and exponent.
    -   Remember: for $1.2345 \times 10^7$, $1.2345$ is the mantissa, and $7$ is the exponent
    -   In Python, maximum is about 3 digits for the exponent and 17 digits for the mantissa
    -   For example, try: `2.0**2000`
        -   `OverflowError`

- **So, be careful when mixing numeric types!**
    -   On June 4, 1996 the European Space Agency launched the first Ariane 5 rocket:
    -   the result of a decade of development, \$8 billion
    -   Exploded 40 seconds after lift-off with a \$500 million satellite payload on board...
    -   Cause was a software error related to a **number type conversion and an overflow**

# Constants

-   Constants are variables with values that the program never changes
-   Reasons to use them:
    -   improves readability of the source code
    -   facilitates easier program modification
-   Good programming practice (style):
    -   place all constant declarations **at the beginning of a program**
    -   use all CAPITALS for constant names

Example: a checkerboard with a set UNIT:

```python
import turtle

UNIT = 50

# draws a square with size UNIT, "filled" sets if it is filled or not
def draw_square(t, filled):
    if filled==True:
        t.begin_fill()
    for i in range(4):
        t.forward(UNIT)
        t.left(90)
    if filled==True:
        t.end_fill()
    
pen = turtle.Turtle()
pen.speed(10)

pen.penup()
pen.goto(-4*UNIT, -4*UNIT) # go to the lower left
pen.pendown()

fill = True
# drawing a row
for i in range(8):
    # draw a column in a row
    for j in range(8):
        draw_square(pen, fill)
        pen.forward(UNIT)
        fill = not fill
    # go back to start and next row
    pen.penup()
    pen.left(90)
    pen.forward(UNIT)
    pen.left(90)
    pen.forward(8 * UNIT)
    pen.left(180)
    pen.pendown()
    fill = not fill

```

Some challenges:

- Add another constant that specifies the number of rows and columns in this checkerboard
- Given a point at (x,y), check the corresponding row and column (use the modulus operator!)