--- slideOptions: theme: white --- # Chapter 3 - Expression and Statement ###### tags: `Computer programming` ## Learning Objectives By the end of this chapter, you should able to: 1. Describe and use expressions in the Python program 2. List out the precedence and associativity of the operators 3. Use type conversion in a Python program 4. Describe the types of statements --- ## Introduction A Python program is composed of **statements** , and a statement is composed of **expressions**. In this chapter, we will study more on expressions and statements, that are the basic elements in composing a Python program. --- ## Expression An expression is a sequence of **operands** and **operators** that _reduces to a single value_. The simplest kind of expression is a _literal_. A literal is used to indicate a special value. ---- There are two kinds of expressions. 1. A _simple expression_ - there is at most one operator, e.g. `2 + 5` whose value is `7` 2. A _complex expression_ - there are more than one operators, e.g. `2 + 5 \* 7` whose value is `37` A simple express can be divided into the following categories. ---- ![](https://i.imgur.com/syh59XX.png) ---- ### Primary expression The _primary expression_ consists of only _one operand without an operator_. A primary expression can be one of the following. - An _identifier_ (for a variable or function), e.g. `a`, `b12`, `price`, `calc`, `INT_MAX`, `SIZE` - A _value_ (that cannot be changed), e.g. `5`, `123.98`, `True`, ``"Welcome"`` - A **parenthesized expression** i.e any expression, including complex expressions can be enclosed in parentheses to make it a primary expression, e.g `(2 * 3 + 4)` ---- ### Binary expression The _binary expression_ is in the form of _operand-operator-operand_. ![](https://i.imgur.com/Dt8sbEz.png) ---- There are several types of binary expressions in Python. In this chapter, we will learn only two, the _additive expression_ and _multiplication expression_. ---- #### Additive expression The operator can be add (`+`) or subtract (`-`), e.g. `3 + 5` give a value of `8`. The operands for `+` and `-` can be integral or floating-point. For strings, the addition operator (+) means _string concatenate_, which combines two strings into one, e.g. `"MFS"` + `"ICT"` gives out `"MFSICT"`. ---- #### Multiplication expression The operator can be one of the following. - Multiply (`*`), e.g. `3 * 5` gives a value of 15. The operands can be integral or floating-point. - Repetition of strings (`*`), e.g. `"MFS" * 3` gives out `"MFSMFSMFS"`. The first operands must be string. - Divide (`/`), e.g. `13 / 2` gives a value of `6.5`. The operands can be integral or floating-point. Notice that it _always returns a float_. - Modulus (`%`) that gives out the remainder of the first operand divided by the second operand, e.g. `17 % 5` gives a value of `2`. The operands can be integral or floating-point, but it must be integral theoretically. ---- ### Unary expression The _unary expression_ comes before the operand. ![](https://i.imgur.com/zUJSDVA.png) ---- The operator can be either one of the following. - Plus (`+`), e.g. `+a`, which gives a positive value of a - Minus (`-`), e.g. `-a`, which gives the negative value of a --- ## Statement A Python program is composed of the statements. There are different types of statements in Python programming language, as shown below. ---- ### Simple statement A _simple statement_ is composed with a single logical line. ---- #### The `pass` statement The _`pass` statement_ is just a pass. It is the shortest statement with no action performed. It may be required for syntactic reasons in some cases. ```python~ pass # pass statement ``` ---- #### Expression statement An _expression statement_ is just the expression. A semicolon (`;`) can be added so that more than one expression can be performed in one line, although it is not preferred. ```Python! expression #expression statement #Perform more than one expression statement in a single line expression; expression; … ``` ---- #### Multi-line statement Statements in Python can be extended to one or more lines using parentheses (`()`), braces (`{}`), square brackets (`[]`), semicolon (`;`), and continuation character slash (`\`). ---- Below shows an example of using continuation characters slash (\). Others would be discussed later. ```Python!= num = 1 + 2 + 3 + \ 4 + 5 + 6 + \ 7 + 8 + 9 print(num) ``` ---- <iframe src="https://trinket.io/embed/python3/0ef08416f7?runOption=run&start=result" width="100%" height="140" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> ---- #### Assignment statements The _assignment statements_ are used to bind / rebind the identifiers to values and to modify attributes or items of objects. ---- ##### Simple assignment The _simple assignment_ is the algebraic expression. The syntax of it is shown below. ```Python! variable = expression ``` ---- The semantics of the assignment is that the expression on the right side is evaluated to produce a value, which is then associated with the variable named on the left side. ![](https://i.imgur.com/fGUWFaG.png) ---- In Python, values may end up anywhere in memory, and variables are used to refer to them. Assigning a variable is like putting one of those sticky notes on the value and marking it as that variable. ![](https://i.imgur.com/z7L7GAw.png) ---- The table below shows some examples. | **Assignment** | **Content of variable** | **Value of expression** | **Content of the variable after the assignment statement is evaluated** | | --- | --- | --- | --- | | `a = 5` | N/A | `5` | `a` is `5` | | `b = x + 1` | `x` is `7` | `8` | `b` is `8` | | `i = i + 1` | `i` is `-5` | `-4` | `i` is `-4` | ---- ##### Augmented assignment The _augmented assignment_ requires that the left operand be repeated as a part of the right expression. There are several types of augmented assignment operators, i.e. `+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `//=`, etc. ---- The table below shows the augmented assignment and their equivalent. | **Augmented assignment** | **Equivalent simple assignment** | | --- | --- | | `x += expression` | `x = x + expression` | | `x -= expression` | `x = x - expression` | | `x *= expression` | `x = x * expression` | | `x /= expression` | `x = x / expression` | | `x %= expression` | `x = x % expression`| | `x **= expression` | `x = x ** expression` | | `x //= expression` | `x = x // expression` | For example, `x *= y + 3` is equivalent to `x = x * (y + 3)`. ---- ##### Simultaneous assignment Python allows _simultaneous assignment_ syntax like the following. ```Python! variable1, variable2, …, variable_n = expression1, expression2, …, expression_n ``` ---- For example, the statement `sum, diff = x + y, x - y`, `sum` would get `x + y`, and `diff` would get `x - y`. We can swap the value of the variables in Python by the following way. ```Python! x, y = y, x ``` ---- #### Import statement The _import statement_ is executed in two steps: 1. Find a module, loading and initializing it if necessary 2. Define a name or names in the local namespace for the scope where the import statement occurs. ---- For example, we can import the math library, which defines lots of functions and values for mathematics, by the following statement. ```Python! import math # Makes the math library available. ``` More details would be discussed later. ---- #### Return statement The _return statement_ terminates a function and returns a value to the calling function (will be discussed in the later chapters). ```python! return expression # return statement ``` --- ### Compound statements The _compound statement_ is a unit of code consisting of zero or more statements with the same indentation. In Python, it is usually indented with 4 spaces (suggested) or 1 tab. Below shown an example of the body of a function. ---- ```python! …… # Statements x = 1 y = 2 z = x # End Block …… ``` --- ## Operators Operators are used to connect one or more operands and give out a single value. The _precedence_ and _associativity_ of operators are going to be discussed in this section. ---- ### Precedence _Precedence_ is the order of the operators in an expression evaluated. The operators that have higher precedence will take action first. For example, the multiplication (`*`) higher precedence than addition (`+`), and hence multiplication (`*`) is done before addition (`+`), thus `2 + 5 * 7` evaluates to `37` rather than 49. The table of operator precedence is listed in Appendix I. ---- ### Associativity The associativity determines the order that operators with the same precedence are evaluated in a complex expression. ---- - A _left-to-right_ associativity, i.e. `3 * 8 / 4 % 4 \* 5` is exactly the same as `((((3 * 8) / 4) % 4) * 5`, and gives a value of `10` ![](https://i.imgur.com/P3NO7UG.png) - A _right-to-left_ associativity. Here are two examples - `a += b *= c -= 5`, which is the same as `(a += (b \*= (c -=5)))`, and also same as `(a = a + (b = b \* (c = c - 5)))` ![](https://i.imgur.com/OHE1Xqd.png) - `a = b = c = d = 0`, is the same as `(a = (b = (c = (d = 0))))`, which assigns `0` to each variable. --- ## Type conversion In Python, the operations must be done by two operands with the _same data type_. If they have different data types, one of them must be converted to such that both of them have the same data type. There are two types of type conversions in Python, namely the _implicit conversion_ and _explicit type conversion (cast)_. --- ### Implicit conversion In Python, when the data type conversion takes place during compilation or during the run time, then it;s call an _implicit data type conversion_. Python handles the implicit data type conversion, so we don;t have to explicitly convert the data type into another data type. ---- ```python!= a = True print("Line 2 - value:", a, "; type:", type(a)) a = a + True # True is presented as 1 in int print("Line 4 - value:", a, "; type:", type(a)) a = a + 1.1 print("Line 6 - value:", a, "; type:", type(a)) ``` ---- <iframe src="https://trinket.io/embed/python3/e7b49a7c61?runOption=run&start=result" width="100%" height="180" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- ### Explicit conversion (cast) We can convert data from one type to another type using _explicit conversion_. It is also known as _type casting_. We can use the following functions to do the conversions. ---- | **Function** | **Description** | **Example** | **Result** | | --- | --- | --- | --- | | `chr(number)` | Converts number to its corresponding ASCII character | `chr(65) ; chr(97)` | `"A" ; "a"` | | `int(str, base)` | Converts any data type to integer base specifies the base in which string is if data type is string. The default value of base is 10, if it is not specified. | `int("35") ; int("35", 10) ; int("35", 8)` | `35 ; 35 ; 29` | | `float()` | Converts any data type to a floating point number, | `float("3.87")` | `3.87` | | `ord()` | Converts a character to integer. | `ord("A")` | `65` | | `hex()` | Converts integer to hexadecimal string. | `hex(35)` | `"0x23"` | | `oct()` | Convert integer to octal string. | `oct(35)` | `"0o43"` | | `bin()` | Convert integer to binary string. | `bin(35)` | `"0b100011"` | | `str()` | Convert the given data type to a string. | `str(35)` | `"35"` | --- ## Chapter summary - Expressions are the fragments of a program that produce data. An expression can be composed of the following components. - **Literals** : a literal is a representation of specific value. For example, 3 is a literal representing the number three. - **Variables** : a variable is an identifier that stores a value - **Operators** : operators are used to combine expressions into more complex expressions. For example, in `x + 3 * y` the operators `+` and `*` are used. ---- - The Python operators for numbers include the usual arithmetic operations of addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), and exponentiation (`**`). - In Python, assignment of a value to a variable is indicated using the equal sign (`=`). ---- - Python automatically converts numbers from one data type to another in certain situations. For example, in a mixed-type expression involving `int` and `float`, Python first converts the `int` into `float` and then uses `float` arithmetic. - Programs may also explicitly convert one data type into another using the function `int()`, `float()` and `str()`. Type conversion functions should generally be used in place of eval for handling numeric user inputs. --- ## Exercise 1. Expressions are built from literals, variables, and operators. A. True B. False 2. Which of the following are _not_ used in expressions? A. variables B. statements C. operators D. literals ---- 3. Which of the following is the most accurate model of assignment in Python? A. sticky-note B. variable-as-box C. simultaneous D. plastic-scale 4. In a mixed-type expression involving `int` and `float`, Python will convert A. `float` to `int` B. `int` to `str` C. both `float` and `int` to `str` D. `int` to `float` ---- 5. Which of the following _cannot_ be used to convert a string of digits into a number? A. `int` B. `float` C. `str` D. `eval` ---- 6. Show the result of evaluating each expression. Be sure that the value is in the proper form to indicate its type (`int` or `float`). a. `4.0 / 10.0 + 3.5 \* 2` b. `10 % 4 + 6 / 2` c. `3 * 10 // 3 + 10 % 3` d. `3 ** 3` 7. Translate each of the following mathematical expressions into an equivalent Python expression. a. $(3 + 4) (5)$ b. $\frac{n(n+1)}{2}$ c. $\frac{y2-y1}{x2-x1}$ ---- 8. Show the string that would result from each of the following string formatting operations. a. `"Look like {1} and {0} for breakfast".format("eggs", "spam")` b. `"There is {0} {1} {2} {3}".format(1, "spam", 4, "you")` c. `"Hello {0}".format("Susan", "Computewell")` d. `"{0:0.2f} {0:0.2f}".format(2.3, 2.3468)` e. `"Time left {0:02}:{1:05.2f}".format(1, 37.374)` --- ## Programming Exercise ### Exercise 1 Write a program that prompts a user for a 5-digit integer and then prints the individual digits of the numbers on a line with 1 space in between the digits. Sample run is as follows. <iframe src="https://trinket.io/embed/python3/7770543455?outputOnly=true&runOption=run&start=result" width="100%" height="150" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> _(Hint: Use the modulus operator %10 to get the rightmost digit and use integer division /10 to remove the rightmost digit.)_ --- ### Exercise 2 Write a program to create a customer's bill for a company. The company sells only five different products: TV, VCR, Remote Controllers, CD Players, and Tape Recorder. The unit prices are $400.00, $220.00, $35.20, $300.00, and $150.00, respectively. The program must read the quantity of each piece of equipment purchased from the keyboard. It then calculates the cost of each item, the subtotal, and the total cost after an 8.25% sales tax. ---- The sample program is shown below. ``` How Many TVs Were Sold? 3 How Many VCRs Were Sold? 5 How Many Remote Controllers Were Sold? 1 How Many CDs Were Sold? 2 How Many Tape Recorders Were Sold? 4 QTY DESCRIPTION UNIT PRICE TOTAL PRICE --- ----------- ---------- ----------- 3 TV 400.00 1200.00 5 VCR 220.00 1100.00 1 REMOTE CTRLR 35.20 35.20 2 CD PLAYER 300.00 600.00 4 TAPE RECORDER 150.00 600.00 ----------- SUBTOTAL 3535.20 TAX 291.65 TOTAL 3826.85 ``` --- ### Exercise 3 Write a program that calculates the change due a customer by denomination; that is, how many $0.1, $0.2, $0.5, $1, $2, $5, $10 coins are needed in a change. The program reads two (floating-point) numbers: the first number is the amount the bill and the second number is the amount the customer paid. The program prints the amount of the change that should be given to the customer, and also the number of each kind of coins. ---- (Assume that only the coins are used for the change.) Sample program: ``` The bill amount : 22.6 The customer pay: 40 The change is : 17.4 The change comprises of 1 x $10 1 x $5 1 x $2 0 x $1 0 x $0.5 2 x $0.2 0 x $0.1 ``` _(Hint: You may need to use the modulus operator %, integer division /, and explicit type casting)_ --- ## Appendix I - Precedence and associativity in Python | **Operator** | **Name** | **Associativity** | | --- | --- | --- | | `()` | Parenthesis | Left to right | | `**` | Exponent | Right to left | | `~` | Bitwise NOT | Left to right | | `*`, `/`, `%`, `//` | Multiplication, Division, Modulos, Floor Division | Left to right | | `+`, `-` | Addition, Subtraction | Left to right | | `>>`, `<<` | Bitwise right and left shift | Left to right | | `&` | Bitwise AND | Left to right | | `^` | Bitwise XOR | Left to right | | `\|` | Bitwise OR | Left to right | | `==`, `!=`, `>`, `<`, `>=`, `<=` | Comparison | Left to right | | `=`, `+=`, `-=`, `*=`, `/=`, `**=`, `//=` | Assignment | Right to left | | `is`, `is not` | Identity | Left to right | | `in`, `not in` | Membership | Left to right | | `and`, `or`, `not` | Logical | Left to right |