# Addition 2+1
# Subtraction 2-1
# Multiplication 2*2
# Division 3/2
# Floor Division 7//4
Whoa! What just happened? Last time I checked, 7 divided by 4 equals 1.75 not 1!
The reason we get this result is because we are using "floor" division. The // operator (two forward slashes) truncates the decimal without rounding, and returns an integer result.
So what if we just want the remainder after division?
# Modulo 7%4
4 goes into 7 once, with a remainder of 3. The % operator returns the remainder after division.
# Powers 2**3
# Can also do roots this way 4**0.5
# Order of Operations followed in Python 2 + 10 * 10 + 3
# Can use parentheses to specify orders (2+10) * (10+3)
Now that we've seen how to use numbers in Python as a calculator let's see how we can assign names and create variables.
We use a single equals sign to assign labels to variables. Let's see a few examples of how we can do this.
# Let's create an object called "a" and assign it the number 5 a = 5
Now if I call a in my Python script, Python will treat it as the number 5.
# Adding the objects a+a
What happens on reassignment? Will Python let us write it over?
# Reassignment a = 10
# Check a
Yes! Python allows you to write over assigned variable names. We can also use the variables themselves when doing the reassignment. Here is an example of what I mean:
# Check a
# Use A to redefine A a = a + a
# Check a
The names you use when creating these labels need to follow a few rules:
1. Names can not start with a number. 2. There can be no spaces in the name, use _ instead. 3. Can't use any of these symbols :'",<>/?|\()!@#$%^&*~-+ 4. It's considered best practice (PEP8) that names are lowercase. 5. Avoid using the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names. 6. Avoid using words that have special meaning in Python like "list" and "str"
Using variable names can be a very useful way to keep track of different variables in Python. For example:
# Use object names to keep better track of what's going on in your code! my_income = 100 tax_rate = 0.1 my_taxes = my_income*tax_rate
# Show my taxes! my_taxes
You can convert from one type to another with the int(), float(), and complex() methods:
x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c))
1.0 2 (1+0j) <class 'float'> <class 'int'> <class 'complex'>
So what have we learned? We learned some of the basics of numbers in Python. We also learned how to do arithmetic and use Python as a basic calculator. We then wrapped it up with learning about Variable Assignment in Python and type conversion.
Up next we'll learn about Strings!