Basic Mathematical Operations
The usage of addition (+), subtraction (-), multiplication (*), and division (/) is the same as in daily life. Multiplication and division will be carried out first, followed by addition and subtraction. Also, the priority of a pair of brackets () will precede others. For example,
y = 4*2.5 - 9/3print(y)
will output 7.0. (How about 4*(2.5 - 9/3)?)
More on Division
There are some variants for division. A double slash // will just retain the integral part while % extracts the remainder (modulus), e.g.
print(20.1/3)print(20.1//3)print(20.1%3) # 2.1? Floating-point error!
produces
6.76.02.1000000000000014
The last item has a very small error compared to the should-be value of 2.1. In fact, this is due to the truncation error of floating-point numbers in a computer. The gray part after the # symbol constitutes a comment, which is for annotation and will not be executed or interpreted.
Exponentiation and Scientific Notation
To compute a number raised to some power (e.g. \( a^b \)), we write a**b in Python. Exponentiation precedes the four basic arithmetic operations above. For example,
print(2**10, 6.7**-0.5)
yields
1024 0.3863337046431279 reasonably. Regarding scientific notation (e.g. \( a \times 10^b \)), a dummy way is to write a*10**b, but a more convenient way is to use the syntax ae+b or ae-b. Using Avogadro’s constant and an electron’s charge as an illustration:
Avo = 6.02e+23e_C = -1.602e-19print(Avo, e_C)
This readily produces 6.02e+23 -1.602e-19.
Implicit Casting
Attentive readers may have noticed that if we mix integers and floats in an expression to be evaluated, the output will be in the form of a float. This is implicit casting in effect, which means that an integer will be automatically converted to a float to make the calculation consistent in this case. Another obvious example will be
print(1+2.5-1.5)
which generates 2.0 (instead of just 2).
Exercise
Convert the two Celsius temperatures \( T_c = 10,25 \) into the Fahrenheit unit. It is better to define a variable to store the Celsius temperature first, and use this variable in the calculation. (The formula for C to F is \( T_f = \frac{9}{5}T_c + 32 \).)
Suggested Solution
T_celsius = 10T_fahrenheit = 9/5 * T_celsius + 32print("Temperature Conversion Result:", T_fahrenheit, "degree F")
This returns Temperature Conversion Result: 50.0 degree F. Now replace 10 by 25 for the second case. Notice that the floating-point format leads to a trailing zero. In the next tutorial, we will start talking about how to format variables for printing out cleanly.







Leave a Reply