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)
produces
6.76.02.1000000000000014
The last item has a very small error compared to the should-be value of 2.1. In fact, it is due to the truncation error of floating-point numbers in a computer.
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 temperature \( 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 + 32)print("Temperature Conversion Result:", T_fahrenheit, "degree F.")
This returns 75.60000000000001. Now replace 10 by 25 for the second case. Notice that the floating-point error makes the output quite ugly. In the next tutorial, we will start talking about how to format variables for printing out cleanly.







Leave a Reply