This notebook uses code snippets and explanations from this course.
In the previous chapter, you have made a first start with programming in Python. We have already seen some basic data types: strings and numerical values. In this chapter, we will further explain the concept of data types and have a closer look at the numerical ones: integers and floats.
If you have questions about this chapter, please refer to the forum on Canvas.
Python is an object-oriented programming language. This means that it treats every piece of data like some kind of object that can be manipulated and passed around. Python has the following basic types of objects:
True
or False
.You can also read about the types in Python in the documentation here, and we will work with each of them during the course. Here's an example of each type:
In [ ]:
a_string = 'test'
an_integer = 4
a_float = 3.14
a_tuple = (2,5)
a_list = [1,2,3,1,2,3,'a','b','c']
a_set = {1,2,3,4,'apple'}
a_dict = {'milk':2, 'cheese':1, 'pickles':45}
a_function = print
a_bool = True
We can use the type()
function to check object types. Let's use it for a selection of our newly defined objects:
In [ ]:
type(a_string)
In [ ]:
type(a_function)
In [ ]:
type(an_integer)
What you need to know at this point is that each type has particular affordances, or associated things that you can do with them. When something is of a numeric type (integer, float), the Python interpreter knows that you can perform mathematical operations with that object. You cannot use those operations with strings, because it doesn't make sense to take the square root of the string "Hello, world!".
It's the same with vehicles and food in real life. Anything that is of the type vehicle can be used to get around and possibly transport goods. But you cannot eat a vehicle. Anything that is of the type food is edible, but it's pretty difficult to use food for transportation (try biking home on a carrot).
So depending on the type, Python interprets objects in a different way and you can do different thing with them. For example, Python will throw a TypeError
if you try to divide one string by another:
In [ ]:
print("Hello" / "World")
Sometimes, the same symbols can act like different operators depending on the type which they are used with. Compare the following two code blocks:
In [ ]:
var1 = 1 + 4
print(var1)
In [ ]:
var2 = "hello " + "there'"
print(var2)
As we can see, “+” means “addition” if we use it with integers and “concatenate” (put together) if we use it with strings. If we try to combine both types, Python will indicate that the operation you are trying to do does not make sense:
In [ ]:
var3 = 4 + "hello"
print(var3)
In [ ]:
x = 2
y = "5"
z = x + y
print(z)
We get again a TypeError
indicating that we cannot combine a string and an integer. Luckily, we can convert the string into an integer by applying int()
to the variable x
.
In [ ]:
x = "5"
y = 2
z = int(x) + y
print(z)
print(type(z))
Similarly, we can convert an integer into a string using str()
, after which it can be concatenated with another string:
In [ ]:
x = 2
y = " apples"
z = str(x) + y
print(z)
print(type(z))
Other types of conversions are possible as well, but of course not all conversions make sense. For example, we cannot make an integer of the string "hello":
In [ ]:
int("hello")
Because variables can change data type, we say that Python uses 'dynamic typing', as opposed to other more 'strict' languages that use 'strong typing'.
We will discuss all of the data types throughout this course. But for now, let's have a closer look at the numerical values that you can use in Python: integers and floats.
So far we have only assigned numbers such as 2 or 365 to our variables. Such whole numbers are called integers in programming, because they don't contain any digits 'after the dot'. Numbers that do have digits after the dot (e.g. 67.278 or 191.200), are called 'floating-point numbers' in programming or simply floats. Note that Python uses dots in floats, whereas some European languages use a comma here. Both integers and floats can be positive numbers (e.g. 70 or 4.36) as well as negative numbers (e.g. -70 or -4.36). You can just as easily assign floats to variables:
In [ ]:
some_float = 23.987
print(some_float)
some_float = -4.56
print(some_float)
On the whole, the difference between integers and floats is of course important for divisions where you often (automatically) end up with floats. This is known as implicit type conversion, or 'coercion':
In [ ]:
x = 5/2
print(x)
There are several mathematical operators defined for both integers and floats, some of which we have already seen above:
Operation | Result |
---|---|
x + y |
sum of x and y |
x - y |
difference of x and y |
x * y |
product of x and y |
x / y |
quotient of x and y |
x // y |
floored quotient of x and y |
x % y |
remainder of x / y |
-x |
x negated |
+x |
x unchanged |
x ** y |
x to the power y |
You will undoubtedly remember from your math classes in high school that there is something called operator precedence, meaning that multiplication, for instance, will always be executed before subtraction. In Python you can explicitly set the order in which arithmetic operations are executed, using round brackets. Compare the following lines of code:
In [ ]:
nr1 = 10-2/4
nr2 = (10-2)/4
nr3 = 10-(2/4)
print(nr1)
print(nr2)
print(nr3)
Using the operators we have learned about above, we can change the variables in our code as many times as we want. We can assign new values to old variables, just like we can put new or more things in the boxes which we already had. Say, for instance, that yesterday we counted how many books we have in our office and that we stored this count in our code as follows:
In [ ]:
number_of_books = 100
Suppose that we buy a new book for the office today: we can now update our book count accordingly, by adding one to our previous count:
In [ ]:
number_of_books = number_of_books + 1
print(number_of_books)
Updates like these happen a lot. Python therefore provides a shortcut and you can write the same thing using +=.
In [ ]:
number_of_books += 5
print(number_of_books)
This special shortcut (+=) is called an operator too. Apart from multiplication (+=), the operator has variants for subtraction (-=), multiplication (*=) and division (/=) too:
In [ ]:
number_of_books -= 5
print(number_of_books)
number_of_books *= 2
print(number_of_books)
number_of_books /= 2
print(number_of_books)
In [ ]:
result = "1" + "3"
In [ ]:
x = 3 + (2 * 5) + (10 - 2) / 3
print(x
In [ ]:
var1 = 365
var2 = 3.14
var3 = "hi there"
In [ ]:
x = 10
y = "5"
z = x / y # fix the code here
print(z)
In [ ]:
nr1 = 2
# your code here