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 can also do things like this, but since we are not storing the result, it cannot be used later. It will also only print out the last statement in the “block”.

428 / 3.2
133.75

Order of operations works as expected.

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
total_assets_estimate
265242.255

Rounding#

Rounding to the nearest integer, or to one decimal place:

# 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

Math operators with strings#

What happens when we try to add strings together?

string1 = 'hello'
string2 = 'world'

print(string1 + string2)
print(string1 + ' ' + string2)
helloworld
hello world

What happens when we multiply a string with a number?

str_mult = 'Finance' * 10
print(str_mult)
FinanceFinanceFinanceFinanceFinanceFinanceFinanceFinanceFinanceFinance