Programs and expressions 0/5

Lesson 4 of 21

Data types and input output

Read numbers, words and decimals, print exactly what is asked, and switch to 64-bit integers when values grow.

Part 1 of 9 Values and their types

Values and their types

These two lines look almost the same:

Sign up to run
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:

Sign up to run
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.

The four types and their names in each language
Kind of valuePythonC++Examples
integerintint, long long42, 0, -7
floating-point numberfloatdouble2.5, 3.0, -0.001
textstrstring"Ada", "7", ""
booleanboolboolPython True, False; C++ true, false