The following are examples of the kinds of Python expressions that we can use.
4 + 5
15 - 12.5
3.4 * 6
Each Python value has a type. 4, 5, 15, and 6 have type int. 12.5 and 3.4 have type float. Float stands for floating point number. Floats are approximations to the real numbers.
Python has two different division operators: / produces a float and // is integer division (it produces an int).
8 / 4
8 // 4
# When writing programs, we can put in English language explanations called comments.
# Whatever comes after the # symbol is not executed.
2 ** 5 # 2 to the power of 5
# The % operator gives the remainder of a division.
# 10 % 3 gives the remainder of 10 // 3
10 % 3
In other words, the fraction 10 / 3 can be rewritten as 3 1/3, so the remainder is 1.
Operator order of precedence (from highest to lowest)
**
- (negation)
*, /, //, % (left to right)
+ (addition), - (subtraction) (left to right)
When programming, it is common to encounter errors. You will learn how to interpret the error messages, so that you can fix your code. Here are a few examples:
3 +
4 + 5 ) * 2
2 * * 5
9 / 0
In addition to the operators shown above, the Python language comes with a set of functions that we can use.
min(45, 23)
max(5.5, 5.52)
abs(-10)
abs(-4 - 8)
type(4)
type(8.25)
round¶Python has a built-in function named round. In the Python shell, run each function call below and record the result:
round(24.2)round(24.5)round(24.9)round(1.234567, 2)round(1.234567, 3)