You are on page 1of 24

Week 4

Expressions and built-in functions.

1
Expressions
An expression is a statement which can be evaluated, and has a value, and a type.
Expressions may contain string literals, numeric constants, variables and operators.
Some examples of expressions:
5 -> value is 5, type is int
‘abc’ ->value is ‘abc’, type is str
7 + 5 -> value is 12, type is int
3.5 * 2 -> value is 7.0, type is float (why?)
x = 6 -> value is 6, type is int
x * 2 -> value is 12, type is int

2
Arithmetic Expressions - Operators

3
Quick Check

What are the results of the following expressions?


12 / 5
12 // 5
10 / 4.0
10 // 4.0
4 / 10
4 // 10
12 % 3
10 % 3
3 % 10
4
Quick Check

What are the results of the following expressions?


12 / 5 = 2.4
12 // 5 = 2
10 / 4.0 = 2.5
10 // 4.0 = 2.0
4 / 10 = 0.4
4 // 10 = 0
12 % 3 = 0
10 % 3 = 1
3 % 10 = 3
5
Concatenating Strings
The + operator can also be used to join two string operands.
The + operator concatenates or joins two strings together and returns a new string.
Both operands must be of type string to use the concatenation operator(+), if one of the
operands is not a string an error will occur.
You may convert the non-string operand to a string by casting.
Examples:

6
Concatenating Strings in print()

Instead of using the comma, we can output multiple strings with the print() statement by
concatenating.

Look at the examples below, what is the difference between the comma and the +
usage?

7
Concatenating Strings in print()

When concatenating within the print statement, remember to convert all operands to
strings first. This is not necessary when joining using the comma.

8
Operator Precedence and Associativity
When different operators appear in the same expression, the normal rules of arithmetic apply.
All Python operators have a precedence and associativity:
• Precedence—when an expression contains two different kinds of operators, which should be applied first?
• Associativity—when an expression contains two operators with the same precedence, which should be
applied first?
To see how precedence works, consider the expression 2 + 3 * 4
• Should it be interpreted as (2 + 3) * 4
• (that is, 20), or rather is 2 + (3 * 4)
According to the rules of precedence, the multiplication operator has a higher precedence than the addition
operator, so the first operation will be multiplication, followed by addition.
To change the order of operations, you may use parentheses. Parentheses have the highest precedence.

9
Operator Precedence

* Parentheses have the highest priority and are evaluated from the innermost set to the outermost set.

10
Quick Check

In what order are the operators evaluated in


the following expressions?

a + b + c + d + e a + b * c - d / e

a / (b + c) - d % e

a / (b * (c + (d - e)))

11
Quick Check

In what order are the operators evaluated in the


following expressions?
a + b + c + d + e a + b * c - d / e
1 2 3 4 3 1 4 2

a / (b + c) - d % e
2 1 4 3

a / (b * (c + (d - e)))
4 3 2 1

12
Examples of Arithmetic Expressions
1. Write a script that inputs a temperature in Fahrenheit from the user and converts to Celsius.

See: convert_fahrenheit.py

2. Write a script that inputs a user’s height (in meters) and weight in kilograms and calculates and displays their
BMI.
𝐰𝐞𝐢𝐠𝐡𝐭 (𝐤𝐠)
𝐁𝐌𝐈 =
𝐡𝐞𝐢𝐠𝐡𝐭 𝟐 (𝐦𝟐 )

13
See: calculate_bmi.py
Assignment Operators

14
Assignment Operators
Output:

15
Built-in Functions
A function is a small program that has a name, takes some input, and does something for us. Sometimes the
function will return the result of a calculation.
Python defines a number of functions that we can use in our programs, that give us functionality. These are called
built-in functions.
We have already used some built-in functions in Python. The print() and input() statements are examples of built
in functions.
Functions have: a name, data required by the function (input arguments) and the result returned by the function
(return value).

Common functions include:


• len(): takes a string and returns the integer length of the string
(number of characters)
• round(): takes a float value and returns the rounded value as a float.
• abs(): takes a float/int value and returns the absolute
value of the argument.
16
Built-in Functions (Math module)
Functions are often grouped according to their functionality. The groups are called packages or
modules.

Modules can contain functions as well as constant values.

One such module is the math module contains common mathematical functions and constants.

To use the functions and constants defined in a module, we must first import the module that
contains the functionality we want to use.

Once we have imported the module, we can access its functionality using the
module_name.function syntax.
17
Math Functions
The math module contains common mathematical functions and constants, which include:

• ceil() : Returns the smallest integer greater than or equal to x.

• floor() : Returns the largest integer less than or equal to x.

• sqrt() : Returns the square root of x.

• pi: Mathematical constant, 3.1415…..

18
Examples with Math functions
1. Write a python script (math_exercise.py) that inputs two values and calculates and display the following:

• Square root of both numbers (store in variables)

• The square root of first number divided by the square root of the second number, rounded up.

• The second number divided by the first number, rounded down (floor vs //).

2. Write a python script (circle_exercise.py) that inputs the radius of a circle and calculates its area and perimeter.

19
Structured Types: str

Strings are structured because you can use indexing to extract individual characters from
a string and slicing to extract substrings.

As discussed before, string objects have built-in functionality.

String objects are immutable, meaning that once the string is created, it cannot be
modified.

Modifying a string always results in the creating of a new string.

20
Updating Strings

name1 “125"
Before:
name2 “CS"

name2 = name2 + name1

name1 “125"
After: “CS"
name2
“CS125"

21
String Functions
Some data types have their own built-in functionality, a good example of this is the string (str) type.

Below are some common functions that we can use with strings. Because strings are immutable, the
functions below that change a string will return a new string.

Function Name Purpose


s.count(s1) Counts how many times the string s1 occurs in s.
s.find(s1) Returns the index of the first occurrence of the substring s1
in s, and -1 if s1 is not in s.
s.rfind(s1) Same as find, but starts from the end of s (the ‘r’ in rfind
stands for reverse)
s.replace(old,new) Replaces all occurrences of the string old in s with the
string new.
s.strip() Removes the leading and trailing whitespace from s.
22
String Functions with Examples

See: string_functions.py 23
Examples with String Functions
1. Write a python script (string_exercise.py) that inputs a string containing a country name, a population
and a life expectancy. Assume each value is separated by a single space. Complete the following:

1. Display the country name.

2. Count the number of 0s in the population. Display the population increased by 10%.

3. Display the life expectancy decreased by 2%.

24

You might also like