In Chapter 1 you printed text and numbers, and you saw that 42 and "42" print the same but are treated differently. This chapter explains why. Everything a program works with is a value, and every value belongs to a type that decides what you can do with it. Once you can see types, a whole family of confusing errors starts to make sense.
Keep the Python shell open while you read (type python in the terminal, or py on Windows). Most examples in this chapter are short enough to try straight in the shell.
2.1 Values: the things programs work with
Think of a kitchen. You have ingredients of different kinds: milk, sugar, rice, tea leaves. Each kind behaves in its own way. You can stir sugar into milk, you can boil rice, but it makes no sense to "stir" a spoon into a song. Before you do anything, you need to know what kind of thing you're holding.
Programs are the same. Every piece of data — a number, a word, a yes-or-no answer — is a value, and every value has a type (also called its data type). The type tells Python:
what kind of thing the value is (a whole number? some text?),
what you can do with it (you can divide numbers, but not sentences),
how to store it in memory.
When you type a value directly into your code, like 42, 3.14 or "hello", it is called a literal: the value is written out literally, exactly as it is. Here are literals of the six basic types you'll meet in this chapter:
print(42)# int: a whole numberprint(3.14)# float: a number with a decimal pointprint("Tokyo")# str: textprint(True)# bool: True or Falseprint(None)# NoneType: "no value"print(2+3j)# complex: a complex number
Output
42
3.14
Tokyo
True
None
(2+3j)
Practice 2.1
Multiple choice
What is a literal?
The word comes from "literally": written out exactly as it is.
42, 3.14 and "hello" are three examples.
The answer is: A value that is typed directly into the code
A literal is a value written directly in the code, such as 42 or "Tokyo".
Predict the output
What does it print?
print(False)print(None)print(1+2j)
print shows None as a word.
Python shows a complex number inside brackets and without spaces.
It prints
False
None
(1+2j)
Each line prints one literal value. A complex number is shown in brackets, with no spaces around the plus sign.
2.2 Asking for the type: type()
Python has a built-in function that tells you the type of any value. It's called type:
Read <class 'int'> as "this value is of type int". The word class is Python's word for a type; you'll make your own classes much later → Chapter 44. For now, class and type mean the same thing.
type works on calculations too. Python first works out the value, then reports the type of the result:
10 / 5 is 2.0, a float, because / always gives a float (you saw this in Chapter 1). "10" + "5" joins two pieces of text into "105", which is still text.
In a script, the shell's automatic display doesn't happen, so wrap type(...) inside print(...):
print(type(99))print(type("99"))
Output
<class 'int'>
<class 'str'>
Here is a summary of the six types. Don't try to memorise it; each one gets its own section below.
Type
Holds
Example literals
int
whole numbers
0, 42, -7, 1_000_000
float
numbers with a fractional part
3.14, -0.5, 2.0, 1.5e3
str
text
"hi", 'Python', ""
bool
truth values
True, False
NoneType
the absence of a value
None
complex
complex numbers
2+3j, 1j
Practice 2.2
Multiple choice
What does this program print?
print(type(10/5))
Python works out the value first, then reports the type of the result.
The result of / always has a decimal point.
The answer is: <class 'float'>
10 / 5 is 2.0, because / always gives a float. So the type is float.
Fill in the blank
Fill in the name of the function that reports what kind of value it is given.
print(("99"))print((99))
The finished program prints:
Target
<class 'str'>
<class 'int'>
The same function goes in both blanks.
Its name is the same word that this chapter uses for int, float and str.
print(type("99"))print(type(99))
type() reports the type of any value. With quotes the value is text, and without quotes it is a whole number.
Put the lines in order
Put the lines in order so that the types appear in the order of the target.
8 is an int, 8.0 is a float, "8" is a str and None has the type NoneType.
2.3 Integers: int
An integer is a whole number: positive, negative or zero, with no decimal point.
print(7)print(-250)print(0)
Output
7
-250
0
No size limit
In many programming languages, integers have a maximum size, and going past it causes strange results. Python integers have no fixed limit. They grow as large as your computer's memory allows. Here is 2 multiplied by itself 100 times (** means "to the power of" → Chapter 4):
That second number is the largest value a typical 64-bit integer can hold in languages such as C or Java. In Python it's just another number, and you can keep going.
Underscores for long numbers
Long numbers are hard to read: is 10000000 one million or ten million? Python lets you put underscores between digits to group them. The underscores are only for your eyes; Python ignores them.
print(1_000_000)# one millionprint(10_000_000)# ten million
Output
1000000
10000000
You can group digits any way you like, but each underscore must sit between two digits: 1__000 (two in a row) and 10_ (at the end) are syntax errors.
No leading zeros
You can't start a whole number with 0 (except zero itself):
print(007)
Output
File "values.py", line 1
print(007)
^^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
The message mentions octal, which leads to the next idea.
Other number bases
We normally count in base 10 (decimal), using the digits 0–9. Computers work in base 2 (binary), using only 0 and 1. Programmers also use base 16 (hexadecimal) and occasionally base 8 (octal). Python lets you write integers in any of these, using a prefix:
Prefix
Base
Digits
Example
Value
none
10 (decimal)
0–9
255
255
0b
2 (binary)
0–1
0b11111111
255
0o
8 (octal)
0–7
0o377
255
0x
16 (hexadecimal)
0–9, a–f
0xff
255
print(0b11111111)print(0o377)print(0xff)
Output
255
255
255
All three are the same value, 255, written in different ways, so print shows it in ordinary decimal. The prefix is only about how you write the number; the value is an ordinary int. You'll see hexadecimal in colour codes (#FF5733) and binary when we look at bitwise operators → Chapter 4.
Practice 2.3
Predict the output
What does it print?
print(1_000+1)print(2,500)print(0b101)
Python ignores underscores between digits. A comma is different: it separates arguments.
In base 2, 101 means one four, zero twos and one one.
It prints
1001
2 500
5
The underscore only groups digits. The comma gives print two arguments. The prefix 0b writes a number in base 2, and print shows it in decimal.
Fix the bug
This should print Seats: 25000, but the number comes out wrong. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
Seats: 25000
Output
Count the arguments that print gets. There are three.
Group the digits with the character that Python ignores inside a number.
print("Seats:",25_000)
A comma inside a number splits it into two arguments. An underscore groups the digits and keeps one number.
Multiple choice
Three of these lines run. Which one is a SyntaxError?
You can group the digits any way you like, so groups of two are allowed.
Each underscore must sit between two digits.
The answer is: print(1__000)
Two underscores in a row are not allowed, because each underscore must have a digit on both sides.
Fill in the blank
Fill in the blank with one million, written as a literal with underscores that group the digits in thousands.
print()
The finished program prints:
Target
1000000
One million is 1 followed by six zeros.
Count three digits from the right, put an underscore, and do it again.
print(1_000_000)
1_000_000 is the same value as 1000000. The underscores are only there to help the reader.
Put the lines in order
Each line writes a number with the digits 11, but in a different base. Put the lines in order so that the output matches the target.
The program in the right order prints:
Target
3
9
11
17
print(0x11)
print(11)
print(0b11)
print(0o11)
0b is base 2, 0o is base 8 and 0x is base 16. No prefix means base 10.
In base 8, 11 means one eight plus one one. Work out the other three in the same way.
print(0b11)print(0o11)print(11)print(0x11)
The same two digits give a larger value in a larger base: one two plus one, one eight plus one, one ten plus one, one sixteen plus one.
Write code
Three bases. Print three lines, each with one integer literal that uses a prefix: first the binary number 1010, then the octal number 17, then the hexadecimal number 2a.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
10
15
42
Output
Each prefix starts with a zero, followed by one letter: b, o or x.
Write the prefix directly in front of the digits, with no space. print shows each value in decimal.
print(0b1010)print(0o17)print(0x2a)
The prefix only changes how you write the number. The value is an ordinary int, and print shows it in base 10.
2.4 Floating-point numbers: float
A float is a number with a fractional part: 3.14, -0.5, 98.6. The name comes from floating point, the way computers store these numbers (the decimal point can "float" to any position).
Any number written with a decimal point is a float, even when the fractional part is zero:
3 and 3.0 are equal in value but different in type. 3. and .5 are allowed short forms, but they're easy to misread, so write 3.0 and 0.5 instead.
Scientific notation
For very large or very small numbers, you can use scientific notation: e means "times ten to the power of".
print(1.5e3)# 1.5 × 10³print(2.5e-4)# 2.5 × 10⁻⁴print(6.022e23)# Avogadro's number
Output
1500.0
0.00025
6.022e+23
A number written with e is always a float, even 1e3 (which is 1000.0). Python itself switches to scientific notation when it prints a float that is very large or very small:
print(1e15)print(1e16)print(0.0001)print(0.00001)
Output
1000000000000000.0
1e+16
0.0001
1e-05
The rule: from 10¹⁶ upwards, and below 0.0001, Python prints floats with e. It's the same value either way, only displayed differently.
Floats are approximate
Here is the most surprising fact in this chapter:
print(0.1+0.2)
Output
0.30000000000000004
This is not a bug in Python. Every language that uses standard floats — C, Java, JavaScript, Go — gives the same answer. The reason is that floats are stored in binary, and most decimal fractions cannot be written exactly in binary.
You already know this problem from decimal. Write ⅓ as a decimal: 0.3333333... The 3s never end, so on paper you must stop somewhere, and the number you write is slightly too small. In binary, the same thing happens to 1/10: it becomes an endless repeating pattern. The computer keeps the first 53 binary digits and drops the rest, so the stored 0.1 is a tiny bit off. Add two slightly-off numbers and the error can show up in the 17th digit.
Most of the time, Python hides this by printing the shortest decimal that rounds to the stored value. That's why print(0.1) shows 0.1 and not the long true value. The hiding stops working when errors add up:
Integers, by contrast, are always exact, however many digits they have. That's one big reason the two types both exist.
Float limits
Unlike integers, floats do have a size limit, at roughly 1.8 × 10³⁰⁸. Beyond that, a calculation gives inf (infinity); below the smallest possible size, numbers become 0.0:
print(1e308*10)print(-1e308*10)print(1e-400)
Output
inf
-inf
0.0
Some operations stop with an error instead of giving inf:
print(2.0**10000)
Output
Traceback (most recent call last):
File "values.py", line 1, in <module>
print(2.0 ** 10000)
~~~~^^~~~~~~
OverflowError: (...)
The part in brackets is a message from your operating system, so it is not the same on every computer. On Linux it reads (34, 'Numerical result out of range'), and on Windows it reads (34, 'Result too large'). The important part is the same everywhere: OverflowError.
2 ** 10000 (with an integer 2) works perfectly well and prints a number with 3011 digits. With the float 2.0, the answer is too big for a float. If you need huge exact numbers, use integers.
Practice 2.4
Predict the output
What does it print?
print(2e3)print(.5+.5)print(0.00001)
A number written with e is always a float, so it is shown with a decimal point.
Below 0.0001, Python prints a float with e and a two-digit power.
It prints
2000.0
1.0
1e-05
2e3 is 2 times 10 to the power 3, as a float. Two floats give a float. A very small float is displayed in scientific notation.
Multiple choice
A program must keep the price $12.50 with no rounding error. What does the chapter recommend?
Floats are approximate. Which number type is always exact?
Scientific notation also makes a float, and a comma makes two arguments.
The answer is: Store 1250 whole cents in an int
Integers are exact, so sums of whole cents never collect rounding errors. Floats are approximate.
Write code
Thirds. Print three lines: first the result of 1 / 3, then the result of 2 / 3, then the result of 1 / 3 + 2 / 3. Let Python do the calculations.
The program prints the lines below. Your program must print exactly these lines.
Example run
0.3333333333333333
0.6666666666666666
1.0
Output
Put each calculation inside its own print(...).
Do not type the digits of the results yourself. Python shows about 16 of them.
print(1/3)print(2/3)print(1/3+2/3)
A float holds about 15 to 17 significant digits, so the endless digits of one third and two thirds are cut and rounded.
2.5 Text: str
A string (type str) is a piece of text: a sequence of characters between quotes. You met strings in Chapter 1.
Strings are so important that they get three chapters of their own: creating them → Chapter 7, picking out parts of them → Chapter 8, and their many built-in tools → Chapter 9.
Practice 2.5
Predict the output
What does it print?
print(type(""))print(type('7'))print("20"+"26")
Anything between quotes is text, even when there is nothing between them.
With two strings, + joins them. It does no maths.
It prints
<class 'str'>
<class 'str'>
2026
The empty string and a single digit in quotes are both str values. Joining two strings of digits gives a longer string of digits.
Fix the bug
This should add one to the year and print the next year. It prints five digits. Fix it so that Python does the addition with numbers.
The program prints the lines below. Your program must print exactly these lines.
Example run
2026
Output
A string made of digits is still text, and + joins text.
Remove the quotes, so that both values are whole numbers.
print(2025+1)
With quotes, the values are text and + joins them. Without quotes they are integers and + adds them.
2.6 True or false: bool
A Boolean (type bool, named after the mathematician George Boole) has only two possible values: True and False. They answer yes-or-no questions: is the user logged in? is the number even? has the game ended?
You'll rarely type True or False yourself. Usually they come from comparisons:
print(5>3)print(10<2)
Output
True
False
Comparisons and the logic you can build with them are the subject of → Chapter 5.
Two details trip up beginners:
Capital letters. It's True and False, with a capital first letter. true is just an unknown name:
print(true)
Output
Traceback (most recent call last):
File "values.py", line 1, in <module>
print(true)
^^^^
NameError: name 'true' is not defined. Did you mean: 'True'?
No quotes."True" in quotes is a four-letter string, not a Boolean:
>>> type("True")
<class 'str'>
Output
Practice 2.6
Predict the output
What does it print?
This uses a comparison (the greater-than sign), which is taught in Chapter 5.
print(7>2)print(type(7>2))print(type("False"))
A comparison answers a yes-or-no question, so its result is a Boolean.
Look at the quotes on the last line.
It prints
True
<class 'bool'>
<class 'str'>
A comparison gives True or False, and both have the type bool. In quotes, "False" is a five-letter string.
2.7 Nothing at all: None
Sometimes you need to say "there is no value here": a form field the user left blank, a search that found nothing, a result that hasn't been calculated yet. Python has a special value for this: None. It is the only value of its type, NoneType.
Notice something odd: typing None in the shell displays nothing at all. The shell shows you every value you type exceptNone, because None means "nothing to show". print does show it, as the word None.
None is not zero, not False, and not the empty string. It's its own thing: no value. Like the other special words, it needs a capital letter: none is a NameError.
Where None comes from: print gives back nothing
Every time you call a function, the function hands a value back to you, called its return value→ Chapter 19. You've only used functions for their effect so far, but you can see the value they give back by printing it. Look at this:
print(print("hi"))
Output
hi
None
Read it from the inside out:
The inner print("hi") runs first. Its effect is to display hi.
Its return value is None. print's job is to show things, not to calculate anything, so it has nothing useful to give back.
The outer print receives that None and displays it.
By contrast, type(42) gives back something useful — the type — which is why we can print it.
Practice 2.7
Predict the output
What does it print?
print(type(print("Lima")))
Read it from the inside out. The inner print runs first and shows its text.
The inner print gives back None. What is the type of None?
It prints
Lima
<class 'NoneType'>
The inner print shows Lima and gives back None. Then type reports the type of that None, and the outer print shows it.
Fix the bug
This should print hi and nothing more, but a second line appears. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
hi
Output
The inner print shows hi. What does it give back to the outer print?
One call of print is enough.
print("hi")
print gives back None. The outer print showed that None on a second line.
2.8 Complex numbers: complex
Python has built-in complex numbers, which you may know from maths as a + bi, where i is the square root of −1. Python follows the engineering convention and writes the imaginary part with j:
.real and .imag read as "the real part of" and "the imaginary part of". The dot is how you reach a value's attributes, the pieces of information it carries → Chapter 45. abs gives the size (magnitude) of a complex number, which is 5 for 3 + 4j by Pythagoras.
You won't need complex numbers unless you work in electrical engineering, signal processing or physics. It's enough to know that they exist and are built in.
Add the real parts together, and add the imaginary parts together.
abs gives the size of a complex number, and the result is a float.
It prints
(4+6j)
5.0
<class 'complex'>
Complex numbers are added part by part. abs(3 + 4j) is the size of the number, which is 5 by Pythagoras, shown as a float.
Fill in the blank
Fill in the blanks. The first line must show the real part of the number, and the second line must show its size.
print((6+8j).)print((6+8j))
The finished program prints:
Target
6.0
10.0
The two parts of a complex number are reached with a dot: one is .imag. What is the other one?
The size (magnitude) comes from a built-in function with a three-letter name.
print((6+8j).real)print(abs(6+8j))
.real reads the real part as a float. abs() gives the size of the complex number.
2.9 Mixing types in a calculation
What happens when one calculation contains values of different types?
int and float: the result is a float
When you combine an int with a float, Python first converts the int to a float, then does the calculation. The result is a float:
print(3+2.5)print(2+2.0)print(10*1.5)
Output
5.5
4.0
15.0
Even 2 + 2.0, whose answer is a whole number, comes out as 4.0. Python picks the type of the result before doing the maths, based only on the types going in. The rule is to move up to the "wider" type, the one that can hold both: int → float → complex.
Division always gives a float
As you saw in Chapter 1, / always produces a float, even for int / int:
>>> 10/2
5.0
>>> 7/7
1.0
Output
If you want whole-number division, there's a separate operator, //→ Chapter 4.
bool acts like a number
True and False can take part in arithmetic, where they behave like 1 and 0:
>>> True+True
2
>>> 5+True
6
>>> 2.5*False
0.0
Output
This isn't an accident: in Python, bool is a special kind of int. Why that is, and why it's useful, is explained in → Chapter 5.
str and numbers don't mix
Text and numbers can't be added together:
print("Age: "+20)
Output
Traceback (most recent call last):
File "values.py", line 1, in <module>
print("Age: " + 20)
~~~~~~~~^~~~
TypeError: can only concatenate str (not "int") to str
This is a TypeError: an operation was used on a type it doesn't support. Concatenate means "join one after the other". With two strings, + joins them. With a string and an int, Python refuses to guess: did you mean the text "Age: 20", or did you want to do maths with the digits? Python's motto is "In the face of ambiguity, refuse the temptation to guess."
For now, the easy fix is a comma, which lets print handle each value separately:
print("Age:",20)
Output
Age: 20
You'll learn how to convert a number into text (and text into a number) in → Chapter 6.
Summary of mixing rules
Expression
Result
Type
int + int
2 + 3 → 5
int
int + float
2 + 3.0 → 5.0
float
int / int
6 / 3 → 2.0
float (always)
bool + int
True + 3 → 4
int
float + complex
1.5 + 2j → (1.5+2j)
complex
str + str
"ab" + "cd" → "abcd"
str
str * int
"ab" * 3 → "ababab"
str
str + int
"ab" + 3
TypeError
Practice 2.9
Multiple choice
Three of these lines run. Which one stops with a TypeError?
True behaves like 1, and an int mixes with a float without trouble.
Text times a whole number repeats the text. Text plus a number is the mix that Python refuses.
The answer is: print("4" + 2)
"4" + 2 could mean the text "42" or the number 6. Python refuses to guess and raises a TypeError.
Put the lines in order
Put the lines in order so that the output matches the target.
The program in the right order prints:
Target
5
5.0
6.0
55
print(2+3.0)
print("5"+"5")
print(10/2+True)
print(2+3)
Find the type of each result. Only int + int prints with no decimal point.
/ gives a float, and True adds 1 to it. Two strings are joined.
int + int stays an int, a float anywhere in the calculation makes the result a float, and + joins two strings.
Write code
Price of one bottle. A pack of 6 bottles costs 9 dollars. Print two lines. On the first line print the label Price of one bottle: and then the price of one bottle, calculated by Python. On the second line print the label Type: and then the type of that same calculation. Use a comma between each label and the value.
The program prints the lines below. Your program must print exactly these lines.
Example run
Price of one bottle: 1.5
Type: <class 'float'>
Output
The price of one bottle is the price of the pack divided by the number of bottles.
Write the same division two times: once after the first label, and once inside type(...).
print("Price of one bottle:",9/6)print("Type:",type(9/6))
/ always gives a float, and the comma lets print show text and a number together without a TypeError.
2.10 Same value, different spellings
A literal is the way you write a value, and one value can often be written in several ways. All of these are the same integer, and the same float:
Python doesn't remember how you typed it. Once the value exists, there is only the value, and Python displays it in one standard way. Similarly 'hi' and "hi" are the same string, and the shell always shows it as 'hi'.
Practice 2.10
Multiple choice
Three of these literals are the same value. Which one is a different value?
e3 means "times ten to the power 3", which is times one thousand.
Work out each value: for example, 15e2 is 15 times one hundred.
The answer is: 1.5e2
1.5e2 is 1.5 times one hundred, which is 150.0. The other three all write 1500.0.
2.11 How Python stores values
Practice 2.11
Multiple choice
Which sentence about the way Python stores numbers is true?
One number type has a fixed number of bits. The other type asks for more memory when it needs more digits.
The fixed size is the reason why floats have a limit and are approximate.
The answer is: A float takes the same number of bytes, whatever its value
A float always has the same fixed size, so it is limited and approximate. An integer grows when it needs more digits, so it has no fixed limit.
+ Practice
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Questions
Check yourself
What is a literal? Give one literal of each of the six types in this chapter.
Show the answer
A literal is a value typed directly into the code. Examples: 42 (int), 3.5 (float), "hi" (str), True (bool), None (NoneType), 2j (complex).
Check yourself
What is the type of each of these: 7, 7.0, "7", 7 / 7, True, None?
Why does 0.1 + 0.2 not print 0.3? Is this a bug in Python?
Show the answer
Floats are stored in binary, and 0.1 and 0.2 can't be written exactly in binary, just as ⅓ can't be written exactly in decimal. The tiny storage errors show up when you add them. It is not a bug; every language with standard floats does the same.
Check yourself
What does print(1_000) show? What does print(1,000) show, and why?
Show the answer
print(1_000) shows 1000. print(1,000) shows 1 0, because the comma makes two separate arguments, 1 and 000, and 000 is zero.
Check yourself
Why does print(true) give an error, but print(True) doesn't?
Show the answer
Python's Boolean values are spelled True and False with a capital letter. true is just a name, and nothing has that name, so it's a NameError.
Check yourself
What is the difference between None and "None"? And between None and 0?
Show the answer
None is the special "no value" value; "None" is a four-letter string. None is not 0 either: 0 is a number, while None means there's no value at all.
Check yourself
Why does print(print("x")) show two lines, and what is the second one?
Show the answer
The inner print("x") displays x, then gives back its return value, None. The outer print displays that None.
Check yourself
An int can be as large as you like, but a float can't. Explain why, in one or two sentences.
Show the answer
A float is always stored in a fixed 64 bits, so there's a largest number it can hold. An int asks for more memory whenever it needs more digits, so it has no fixed limit.
Check yourself
What is the type of 2 + 2.0, and what is its value?
Show the answer
float, with the value 4.0. Mixing an int with a float always gives a float.
Check yourself
You need to store a bank balance in dollars and cents. Why is a float a poor choice, and what could you use instead?
Show the answer
Floats are approximate, so sums of money can come out a tiny bit wrong, like 0.30000000000000004. Store whole cents in an int ($12.50 is 1250), or use Decimal.
Big numbers. The world's population is roughly eight billion one hundred million. Print that number using underscores to group the digits in thousands. Then print one trillion the same way.
Print the population first, then one trillion.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
8100000000
1000000000000
Output
One billion is 1 followed by nine zeros. One hundred million is 1 followed by eight zeros.
Put an underscore after every group of three digits, counting from the right. One trillion is 1 followed by twelve zeros.
print(8_100_000_000)print(1_000_000_000_000)
Eight billion one hundred million is 81 followed by eight zeros. One trillion is 1 followed by twelve zeros.
print(8_100_000_000)print(1_000_000_000_000)
Output
8100000000
1000000000000
Write code · Easy
Light-year. Light travels about 300,000 km every second. Print the number of kilometres light travels in a 365-day year. Then print the same distance in metres, using scientific notation somewhere in your calculation.
Print the distance in kilometres first, then the distance in metres.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
9460800000000
9460800000000000.0
Output
Find the number of seconds in a year first: 60 seconds, 60 minutes, 24 hours and 365 days, all multiplied.
One kilometre is one thousand metres. One thousand in scientific notation is 1e3.
Chessboard rice. A king places 1 grain of rice on the first square of a chessboard, 2 on the second, 4 on the third, doubling each time. The total on all 64 squares is 2⁶⁴ − 1. Print it. Then print it as a float by adding 0.0, and explain in a comment why the two printed numbers look different.
Print two lines: the integer first, then the float.
The program prints the lines below. Your program must print exactly these lines.
Example run
18446744073709551615
1.8446744073709552e+19
Output
The chapter shows that ** means "to the power of". Write the total as 2 ** 64 - 1.
For the second line, write the same calculation and put + 0.0 at the end.
print(2**64-1)print(2**64-1+0.0)# The int is exact. The float keeps only about 16 significant digits,# so the last few digits are rounded away and it's shown with e+19.
print(2**64-1)print(2**64-1+0.0)# The int is exact. The float keeps only about 16 significant digits,# so the last few digits are rounded away and it's shown with e+19.
Output
18446744073709551615
1.8446744073709552e+19
Write code · Medium
Float explorer. Print 0.1 + 0.2 + 0.3 and 0.3 + 0.2 + 0.1. Do you get the same answer? Write a comment explaining what you see.
Print two lines, in the order given in the task.
The program prints the lines below. Your program must print exactly these lines.
Example run
0.6000000000000001
0.6
Output
Write each sum exactly as the task shows it, one print for each sum.
Python adds from left to right, and each addition rounds its result to the nearest float.
print(0.1+0.2+0.3)print(0.3+0.2+0.1)# Not the same! Each addition rounds its result to the nearest float,# so adding in a different order collects different rounding errors.
print(0.1+0.2+0.3)print(0.3+0.2+0.1)# Not the same! Each addition rounds its result to the nearest float,# so adding in a different order collects different rounding errors.
Output
0.6000000000000001
0.6
Write code · Medium
Mixed-type table. For each of these, print the value and its type on the same line: 4 + 4, 4 + 4.0, 4 / 4, 4 * True, "4" * 4.
Print five lines, in the order given. On each line, give print the value and then its type, with a comma between them.
The program prints the lines below. Your program must print exactly these lines.
Dollars and cents. A shop sells three sweets at $0.10, $0.20 and $0.30. Print the total using floats. Then print the total correctly by working in cents (whole numbers), and finally print the dollar amount by dividing the cents total by 100. Explain in a comment why the cents version is safer.
Print three lines with these labels: Total with floats:, Total in cents: and Total in dollars:. Use a comma between the label and the calculation.
The program prints the lines below. Your program must print exactly these lines.
Example run
Total with floats: 0.6000000000000001
Total in cents: 60
Total in dollars: 0.6
Output
In cents, the three prices are 10, 20 and 30. These are whole numbers, so the sum is exact.
For the last line, put the cents total in brackets and divide it by 100.
print("Total with floats:",0.10+0.20+0.30)print("Total in cents:",10+20+30)print("Total in dollars:",(10+20+30)/100)# Whole numbers are exact, so adding cents never collects rounding# errors. We only divide once, at the very end, to display dollars.
print("Total with floats:",0.10+0.20+0.30)print("Total in cents:",10+20+30)print("Total in dollars:",(10+20+30)/100)# Whole numbers are exact, so adding cents never collects rounding# errors. We only divide once, at the very end, to display dollars.
Output
Total with floats: 0.6000000000000001
Total in cents: 60
Total in dollars: 0.6
Write code · Hard
Find the limits. Print 2 ** 1000 (an integer). Then print 2.0 ** 1000 (a float). Then try 2.0 ** 1024 and read the error. In a comment, explain why the integer version works but the float version fails.
This one is not checked automatically. Run your program, then compare it with the book's answer.
Output
Show the book's answer
print(2**1000)print(2.0**1000)print(2.0**1024)# Integers grow to any size. Floats are limited to about 1.8e308,# and 2 to the power 1024 is just past that limit.
Output
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
1.0715086071862673e+301
Traceback (most recent call last):
File "e8.py", line 3, in <module>
print(2.0 ** 1024)
~~~~^^~~~~~
OverflowError: (...)
Write code · Hard
Hex colours. Web colours are written as three hexadecimal numbers for red, green and blue, like #FF8800. Print the red, green and blue amounts of #FF8800 as ordinary decimal numbers, using 0x literals.
Print the red amount first, then green, then blue.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Red: 255
Green: 136
Blue: 0
Output
Cut the six characters after the # into three pairs.
Write 0x in front of each pair. print shows the value in decimal.
Hexadecimal digits can be upper or lower case: 0xFF and 0xff are the same.
Chapter project: Concert fact card
Project
Print a fact card for a concert. There are no variables yet, so every line is one print with a label, a comma, and then a literal or a calculation. Print these six lines, in this order:
the label Tickets sold: and the number twelve thousand five hundred, written with an underscore
the label Ticket price in cents: and the price of one ticket, which is 49 dollars and 50 cents, as a whole number of cents
the label Income in cents: and the number of tickets multiplied by the price in cents
the label Income in dollars: and the same multiplication, divided by 100
the label Type of the income in dollars: and the type of the calculation from line 4
the label Power of the stage lights in watts: and twenty-four thousand, written in scientific notation
Let Python do every calculation. Before you run the program, decide for each line whether it will show an int or a float.
The program prints the lines below. Your program must print exactly these lines.
Example run
Tickets sold: 12500
Ticket price in cents: 4950
Income in cents: 61875000
Income in dollars: 618750.0
Type of the income in dollars: <class 'float'>
Power of the stage lights in watts: 24000.0
Output
One dollar is 100 cents, so 49 dollars and 50 cents is 4950 cents. Money is safest as a whole number of cents.
For lines 3 and 4, write the multiplication again: there are no variables yet. In line 5, put the whole calculation of line 4 inside type(...).
Twenty-four thousand is 2.4 times ten to the power 4. Scientific notation writes that with the letter e.
print("Tickets sold:",12_500)print("Ticket price in cents:",4950)print("Income in cents:",12_500*4950)print("Income in dollars:",12_500*4950/100)print("Type of the income in dollars:",type(12_500*4950/100))print("Power of the stage lights in watts:",2.4e4)
The card uses an underscore to group digits, whole cents for exact money, / which always gives a float, type() to confirm it, and scientific notation, which also always gives a float.