Values and their types
These two lines look almost the same:
print(7 + 7)
print("7" + "7")The first prints 14 and the second prints 77. In the first line 7 is a number, so + adds. In the second, "7" is a piece of text that happens to contain a digit, so + sticks the two pieces of text together.
So the same + did two different things. What changed is the data type, or just type, of the values: whether each one is a number or a piece of text. The type tells Python what a value means and what you can do with it. You choose the type by how you write the value: digits on their own make a number, and quotes make text.
You have already run into this: every program so far called int on each piece of its input. That is because a judge sends the input as text. When the input line is 2 5, your program gets the characters 2, space, 5, so the piece "2" is text, just like "7" above. int turns it into the number 2, and only then can you do arithmetic with it.
Definition
A data type is a kind of value. It fixes which values are possible and which operations work on them.
The four basic types
Almost every program in this course works with four types. Here is one value of each, with Python telling you its type:
count = 42
price = 2.5
name = "Ada"
done = False
print(count, type(count))
print(price, type(price))
print(name, type(name))
print(done, type(done))Python details
type(x) reports the type of the value x names. Digits with no decimal point make an int, a decimal point makes a float, and quotes make a str.
An integer is a whole number such as 42, 0 or -7. A floating-point number, or float, has a fractional part, such as 2.5. A string is text between quotes. A boolean is one of the two truth values, True and False; a comparison such as 5 > 3 gives one.
Other kinds of data, such as a date or a table of results, have no type of their own here. Programs build them out of these four, with the lists, dictionaries and classes of later lessons.
| Kind of value | Python | C++ | Examples |
|---|---|---|---|
| integer | int | int, long long | 42, 0, -7 |
| floating-point number | float | double | 2.5, 3.0, -0.001 |
| text | str | string | "Ada", "7", "" |
| boolean | bool | bool | Python True, False; C++ true, false |
Reading input of each type
So far every input you have read was whole numbers. Input can also contain words and decimals, and you turn each piece into the type it stands for. Say a line tells you what someone bought, how many, and the price of one: pens 3 1.25. This program reads that line and prints the item and the total cost:
item, count, price = input().split()
count = int(count)
price = float(price)
print(item, count * price)Python details
float turns text such as "1.25" into a float, the way int turns "3" into an integer. item needs no conversion, since a word is already text.
After split, all three pieces are strings: "pens", "3" and "1.25". The word can stay a string. The other two we convert: int makes an integer out of "3", and float makes a float out of "1.25". Notice that count = int(count) points the name count at the new integer, so a name that held a string now holds a number. Python allows that because in Python the type belongs to the value, and a name can point at a value of any type.
Turning a value of one type into the matching value of another is called type conversion. In Python you convert by calling the name of the type you want, like int(...). Here are the conversions you will use most:
| Conversion | Code | Result |
|---|---|---|
| text to integer | int("42") | 42 |
| text to float | float("2.5") | 2.5 |
| number to text | str(42) | "42" |
| text with a fraction to integer | int("3.5") | stops with ValueError |
| float to integer | int(3.99) | 3, the fraction cut off |
| float to the nearest integer | round(3.99) | 4 |
Text becomes a number only when it spells one, and int accepts only whole numbers, so int("3.5") stops the program. Converting a float to an integer cuts off the fraction instead of rounding, which is why int(3.99) is 3. round gives the nearest integer instead, and a value exactly halfway goes to the even neighbour: round(2.5) is 2 and round(3.5) is 4.
Deeper read: when types are checked
Because the type belongs to the value, Python checks types only when it reaches an operation: "3" * 1.25 stops with TypeError on the line that tries it, and not before. Checking types while the program runs is called dynamic typing. C++ checks every line before the program runs, which is called static typing.
Python lets you write down the type you intend a name to hold, as a type hint: a colon and the type after the name, as in count: int = 3. Python itself ignores hints, so count = "three" on the next line still runs. A type checker, a separate tool such as mypy or Pyright, reads the program without running it and reports each value that does not match its hint. Many code editors run one as you type, which brings some of static typing's early warnings to Python.
Operators and types
We have now seen + add numbers and join text, and the receipt program multiply an integer by a decimal. In general, what an operator does depends on the types of the values around it. Guess what each line below prints, then run it to check.
print(7 + 2)
print(7.0 + 2)
print("7" + "2")
print("ab" * 3)
print(7 / 2)
print(7 // 2)Python details
/ always gives a float, even for 6 / 2, which is 3.0. // divides and rounds down, and with two integers its result is an integer.
When both values are integers, + adds them and gives an integer. When one is a float, the integer is first converted to a float, so 7.0 + 2 is the float 9.0, and the receipt's count * price was the float 3.75. Strings have their own meanings for the same symbols: + joins two strings, and * repeats a string a whole number of times.
Integer sizes and overflow
Integers are exact: 2 + 3 is 5, with no rounding anywhere. The question is how large an integer can get, and here Python and C++ are very different.
A Python integer has no fixed limit. It uses as much memory as its value needs, so print(2 ** 100) shows all 31 digits of 1267650600228229401496703205376.
You will still see fixed sizes in problem statements, because most other languages, C++ among them, store an integer in a fixed number of bits. A bit is a single 0 or 1, the smallest thing a computer stores. One bit has 2 patterns, two bits have 4 (00, 01, 10, 11), and each extra bit doubles the count, so 32 bits have patterns. Half of them are used for negative numbers, and one of the rest for zero, so the largest integer that fits in 32 bits is
In a fixed size, a result too large to fit is called overflow. A Python integer grows instead. When a statement promises that its answer fits in a 64-bit integer, the limit it means is
| Type | Size | Range | Exact? |
|---|---|---|---|
int | grows as needed | limited only by memory | yes |
float | 64 bits | up to about | about 16 significant digits |
The largest value a program computes
A problem's Constraints section tells you its largest inputs, and from those you can work out the largest value your program will compute. In Python you rarely need the answer, but it is a good habit, and it is the first thing a C++ programmer checks. Here is a problem whose inputs fit in 32 bits but whose answer does not.
Theatre Square is by metres, to be paved with square stones of side . Stones cannot be broken, but they may stick out past the edge. The input is , and , each between 1 and , and the output is the fewest stones that cover the square. The official sample is 6 6 4, and the answer is 4.
Along a 6-metre side, one 4-metre stone leaves 2 metres uncovered, so the side needs 2 stones, the second sticking out by 2 metres. The other side also needs 2, and . In general a side of length needs stones rounded up.
Integer division // rounds down, so we need a small trick to round up: add before dividing. If divides exactly, the extra is not enough to reach the next multiple of and changes nothing. If anything is left over, it pushes the total past the next multiple, which adds the one extra stone. For the sample, , and for an 8-metre side as well, since two stones fit exactly.
The largest answer comes from a by square paved with 1-metre stones:
A Python integer holds exactly, so the program needs nothing special.
n, m, a = map(int, input().split())
across = (n + a - 1) // a
down = (m + a - 1) // a
print(across * down)Step through a product that outgrows an int
Here is the same program with the input written in. Pick an input and step through it; the last one is the largest the limits allow.
With 3 5 10, one stone is larger than the whole square, so each side needs one stone: .
With the largest input, across and down are each and their product is , more than 32 bits can hold. Python stores it exactly.
Floating-point numbers
Integers are exact. Floats are not, and you can see it with the receipt program: give it pens 3 1.10, and instead of 3.3 it prints pens 3.3000000000000003. Here is that product with two more like it:
print(3 * 1.10)
print(0.1 + 0.2)
print(4.35 * 100)Here is why. A float stores a number in binary, built from powers of 2 instead of powers of 10, and keeps about 16 significant digits, that is, 16 digits counted from the first one that is not zero. Most decimal fractions, 1.10 and 0.1 among them, cannot be written exactly in binary, as the Deeper read below shows. So when you write 1.10, you get the nearest float to it, which is slightly more than 1.1. Multiply by 3 and that tiny error comes along into the result.
The error is about of the value, so most of the time you won't notice it. You do notice when a result has to be exact. Say you want 4.35 dollars in cents. You would expect int(4.35 * 100) to be 435, but it is 434: the product lands just below 435, and int cuts off the fraction. Floats you expect to be equal can also differ, since 0.1 + 0.2 and 0.3 are stored as different numbers. This is also why a judge accepts a decimal answer that is close enough instead of asking for exact digits.
Deeper read: why 0.1 has no exact binary form
In decimal, never ends, 0.3333…, because 3 divides no power of 10. Binary has the same problem with any fraction whose denominator is not a power of 2. has the factor 5 in its denominator, so in binary it repeats forever:
A 64-bit float keeps 53 binary digits and rounds the rest, so the stored value of 0.1 is exactly 0.1000000000000000055511151231257827… .
Almost every processor stores floats in the same 64-bit format, fixed by the IEEE 754 standard in 1985, which is why the Python and C++ listings above print the same 17 digits.
Printing a decimal answer
Since a float is approximate, a problem with a decimal answer tells you how close is close enough, and it is up to you how many digits to print. In Python you can usually leave that to print, which shows as many digits as it takes to tell the float apart from its neighbours.
Circle Pond gives an integer radius between 1 and 100 and asks for the circumference . For the input 1 the official answer is 6.28318530717958623200; for 73 it is 458.67252742410977361942.
An answer is accepted when its error, how far it is from the correct answer, is at most , or when that error divided by the correct answer is. For , 6.28 is off by about 0.003, so the judge accepts it; 6 is off by 0.28, so the judge rejects it.
r = int(input())
c = 2 * math.pi * r
print(c)Python details
math.pi is the float closest to . print shows 16 significant digits here.
r is an integer and math.pi is a float, so 2 * math.pi * r converts the integer and gives a float. The program prints 16 significant digits where the official answer shows 20 decimal places, and the judge accepts it: the allowed error is , and this answer's relative error is below .
Common mistakes
Reading a decimal as an integer.
- Where it breaks
- On the input
1.25, Python'sint(input())stops withValueError: invalid literal for int() with base 10: '1.25'. In C++,cininto anintreads 1 and leaves.25, so the next read into adoublegets 0.25. - The fix
- Read a decimal with
float(...)in Python, or into adoublein C++.
Storing the answer in a
long longbut multiplyingintvalues (C++).- Where it breaks
- With
int across, down;, the linelong long stones = across * down;still overflows: the product is computed as anintbefore it is stored. Theatre Square with1000000000 1000000000 1, compiled with GCC, prints-1486618624instead of1000000000000000000. - The fix
- Declare the inputs and every value in the calculation
long long, as the listing does.
Putting a decimal answer in an
int(C++).- Where it breaks
- In Circle Pond,
int c = 2 * numbers::pi * r;compiles and cuts 6.28… down to 6, and the judge rejects6for . - The fix
- Store the result in a
doubleand print it withfixed << setprecision(10).
Expecting integer division to keep the fraction (C++).
- Where it breaks
- With
int a = 3, b = 4;,cout << (a + b) / 2prints3for the average of 3 and 4, not3.5. - The fix
- Make one side a
double:(a + b) / 2.0prints3.5. In Python,/already gives 3.5.
Converting a float to an integer to get a whole number.
- Where it breaks
4.35 * 100is 434.99999999999994, soint(4.35 * 100)in Python and(int)(4.35 * 100)in C++ give434.- The fix
- Round instead:
round(4.35 * 100)gives 435 in both languages. Better still, keep the quantity in integers from the start (435 cents).
Recall What does `7 / 2` give in Python, and what does it give in C++? Why do they differ?
Python gives the float 3.5, because its / always produces a float. In C++ both values are ints, so / is integer division and gives 3. Python writes that operation as 7 // 2.
Recall In Theatre Square with $n = m = 100{,}000$ and $a = 1$, does the answer fit in a 32-bit integer?
No. The answer is , which is larger than . A C++ program needs a long long; a Python integer holds it as it is.
Key terms
| Term | Meaning |
|---|---|
| data type | A kind of value; it fixes which values are possible and which operations work on them. |
| integer | A whole number: int in Python, int or long long in C++. |
| floating-point number | A number with a fractional part, stored with about 16 significant digits: float in Python, double in C++. |
| string | A piece of text, written between quotes: str in Python, string in C++. |
| boolean | One of the two values true and false. |
| type conversion | Turning a value of one type into the matching value of another, as int("42") turns text into 42. |
| bit | A single 0 or 1; bits have patterns. |
| overflow | A result too large for its type. Python integers never overflow; in C++ the program continues with a wrong value. |
| undefined behavior (C++) | An operation the C++ standard sets no rule for, such as an int overflow; the result can differ between compilers. |
| static and dynamic typing | Checking types before the program runs, as C++ does, or while it runs, as Python does. |
| type checker (Python) | A tool that reads a program without running it and reports values that do not match their type hints. |
