Math#
Basic Math#
Create a new variable which is the sum of two other variables. Then print out the result.
number1 = 459
number2 = 833
number3 = number1 + number2
print('The answer =', number3)
The answer = 1292
We can also evaluate expressions directly in the print statement.
print(number2 - number1)
374
We could also do things like this:
428 / 3.2
133.75
but since we are not storing the output, we will not be able to reference it later.
Python can handle the correct order of operations:
10 / (2 + 3)
2.0
Calculate an estimate for total assets:
num_companies = 15
avg_assets = 17682.817
total_assets_estimate = num_companies * avg_assets
# let's also print the result with nice formatting
print(f'The total assets estimate is ${total_assets_estimate:,.0f}')
The total assets estimate is $265,242
Rounding#
We can easily round to the nearest integer, or to any number of decimal places. However, keep in mind that rounding is not the same thing as formatting the output in a print statement with f strings. Formatting the output is just for display purposes, and does not change the underlying value, whereas rounding does change the underlying value. For this reason, avoid rounding in your code unless you have a good reason to do so.
# nearest integer
rounded_value = round(total_assets_estimate)
print(rounded_value)
# round to one decimal place
rounded_value = round(total_assets_estimate, 1)
print(rounded_value)
265242
265242.3
Exponents#
\(2^3\) (frequently written 2^3
in other programs like Excel) is written using **
in Python:
2**3
8
Integer division and the modulus operator#
Integer division does not give you a decimal. It ignores the remainder.
print(10 // 3)
print(12 // 5)
3
2
The modulus operator is an operator that gives you the remainder.
print(10 % 3)
print(12 % 5)
1
2
Another example:
whole_int = 19 // 5
remainder = 19 % 5
print(f'5 goes into 19 → {whole_int} times with a remainder of {remainder}')
5 goes into 19 → 3 times with a remainder of 4
Math operators with strings#
You might think that we can only use these operators with numbers, but what happens when we try to use them with strings?
Adding strings:
string1 = 'Hello'
string2 = 'World'
print(string1 + string2)
HelloWorld
What happens when we multiply a string by a number?
str_mult = 'Finance' * 10
print(str_mult)
FinanceFinanceFinanceFinanceFinanceFinanceFinanceFinanceFinanceFinance