Number and string operations¶
Numbers¶
References: - https://docs.python.org/3/tutorial/introduction.html#numbers - https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator
Arithmetic operations¶
Addition¶
>>> 2 + 12
14
Subtraction¶
>>> 2 - 12
-10
Multiplication¶
>>> 2 * 4
8
Division, with a float as the answer¶
The division operator of /
returns a float (decimal) number by default:
Whole number division¶
To divide 2 numbers and only get a whole number, use a double forward-slash: //
>>> 11 // 7
1
Get the remainder of a division operation¶
This is also known as the modulo operation, which uses the percent sign as its operator:
>>> 7 % 5
2
Built-in functions for numbers¶
Round a fractional number to the nearest n decimal places¶
Use round
and pass in a number as second argument indicating the number of decimal places to round to.
>>> round(8.23593, 1)
8.2
Convert an integer to a float¶
Use the float()
class method and pass in an integer as an argument. The returned value will an equivalent number, but with a data type of float:
>>> float(42)
42.0
>>> type(float(42))
float
Convert a float to an int; or, truncate a float to a whole number¶
Use the int()
class function to truncate a float – note that the result will be an integer, but not what you would get if you used the round
function:
>>> int(4.999)
4