← All concepts

Lecture 1

Data types and converting between them

Every value has a type — int, float, str or bool — and the type decides what you can do with it.

The four types

Whole numbers are int, numbers with a decimal point are float, anything in quotes is a str (string), and True/False are bool. type() tells you which one you have.

print(type(42))
print(type(3.0))
print(type("42"))
print(type(True))

Output

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

Quotes change everything

With strings, + joins and * repeats; with numbers they add and multiply. Text read from a file is always a string, so convert it before doing maths.

print("12" + "3")
print(int("12") + 3)
print(str(4) + " wells")

Output

123
15
4 wells

Going further

For the advanced questions.

Conversions have rules

int() on a float cuts off the decimal part — it does not round. int() cannot read text with a decimal point (ValueError): go through float() first. Division with / always gives a float.

print(int(7.9))
print(int(float("3.5")))
print(10 / 2)

Output

7
3
5.0