Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 2

Values and Types

This lesson goes with Episode 2 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

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 number
print(3.14)          # float: a number with a decimal point
print("Tokyo")       # str: text
print(True)          # bool: True or False
print(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?

Choose one answer

Predict the output

What does it print?

print(False)
print(None)
print(1 + 2j)

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:

>>> type(42)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("Tokyo")
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(None)
<class 'NoneType'>
>>> type(2 + 3j)
<class 'complex'>

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:

>>> type(10 + 5)
<class 'int'>
>>> type(10 / 5)
<class 'float'>
>>> type("10" + "5")
<class 'str'>

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))
Choose one answer

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'>

Put the lines in order

Put the lines in order so that the types appear in the order of the target.

The program in the right order prints:

Target

<class 'int'>
<class 'float'>
<class 'str'>
<class 'NoneType'>
  1. print(type(8.0))
  2. print(type(8))
  3. print(type("8"))
  4. print(type(None))

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):

print(2 ** 100)
print(2 ** 64 - 1)

Output

1267650600228229401496703205376
18446744073709551615

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 million
print(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)

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

Multiple choice

Three of these lines run. Which one is a SyntaxError?

Choose one answer

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

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
  1. print(0x11)
  2. print(11)
  3. print(0b11)
  4. print(0o11)

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

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:

>>> type(3)
<class 'int'>
>>> type(3.0)
<class 'float'>
>>> type(3.)
<class 'float'>
>>> .5
0.5

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:

print(0.1 + 0.1 + 0.1)
print(0.1 * 10)
print(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1)
print(1.1 * 3)

Output

0.30000000000000004
1.0
0.9999999999999999
3.3000000000000003

0.1 * 10 happens to round to exactly 1.0, but adding 0.1 ten times collects ten small errors and doesn't.

What this means for you:

  • Floats are perfect for measurements — heights, temperatures, distances, scientific data — where tiny errors don't matter.
  • Never test two floats for exact equality. Check whether they are close instead → Chapter 5.
  • Don't use floats for money. Store amounts as whole cents in an int, or use the Decimal type made for exact decimal arithmetic → Chapter 17.

Precision

A float holds about 15 to 17 significant digits. Anything beyond that is rounded away:

print(123456789.123456789)
print(1 / 3)
print(22 / 7)

Output

123456789.12345679
0.3333333333333333
3.142857142857143

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)

Multiple choice

A program must keep the price $12.50 with no rounding error. What does the chapter recommend?

Choose one answer

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

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.

>>> type("Hello")
<class 'str'>
>>> type('A')
<class 'str'>
>>> type("")
<class 'str'>

A few things worth knowing now:

  • A single character, like 'A', is still a str. Python has no separate "character" type.
  • "" is the empty string: text with no characters in it. It's a real value, just empty — like a blank sheet of paper.
  • A string made of digits is still text. "2025" is four characters, not a number:
>>> type(2025)
<class 'int'>
>>> type("2025")
<class 'str'>

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")

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

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?

>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

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'>

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"))

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.

>>> type(None)
<class 'NoneType'>
>>> None
>>> print(None)
None

Notice something odd: typing None in the shell displays nothing at all. The shell shows you every value you type except None, 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:

  1. The inner print("hi") runs first. Its effect is to display hi.
  2. Its return value is None. print's job is to show things, not to calculate anything, so it has nothing useful to give back.
  3. 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")))

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

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:

>>> type(3 + 4j)
<class 'complex'>
>>> (3 + 4j) + (1 - 2j)
(4+2j)
>>> (3 + 4j).real
3.0
>>> (3 + 4j).imag
4.0
>>> abs(3 + 4j)
5.0

.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.

Practice 2.8

Predict the output

What does it print?

print((1 + 2j) + (3 + 4j))
print(abs(3 + 4j))
print(type(2j))

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

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

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

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?

Choose one answer

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
  1. print(2 + 3.0)
  2. print("5" + "5")
  3. print(10 / 2 + True)
  4. print(2 + 3)

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'>

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:

print(255, 0xff, 0b11111111, 2_55)
print(1500.0, 1.5e3, 1_500.0, 15e2)

Output

255 255 255 255
1500.0 1500.0 1500.0 1500.0

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?

Choose one answer

2.11 How Python stores values

Practice 2.11

Multiple choice

Which sentence about the way Python stores numbers is true?

Choose one answer

+ 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?

Show the answer

int, float, str, float (because / always gives a float), bool, NoneType.

Check yourself

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.

Predict the output

Predict the output

print(type(10))
print(type(10.0))
print(type("10"))
print(type(10 / 2))

Predict the output

print(5 + 2.0)
print(True + True + True)
print("5" * 3)
print(0x10, 0b10, 1_0)

Predict the output

print(2.5e2)
print(3e-2)
print(1e16)
print(0.1 * 3)

Fix the bug

Fix the bug

This should print the Boolean value true.

The program prints the lines below. Your program must print exactly these lines.

Example run

True

Fix the bug

This should print the number seven.

The program prints the lines below. Your program must print exactly these lines.

Example run

7

Fix the bug

This should print Age: 21.

The program prints the lines below. Your program must print exactly these lines.

Example run

Age: 21

Fix the bug

This should print one million, but it prints 1 0 0.

The program prints the lines below. Your program must print exactly these lines.

Example run

1000000

Coding problems

Write code · Easy

Type detective. Print the type of each of these values on its own line: -12, 0.0, "0", False, None, 1j.

Print six lines, in the order in which the values are listed.

The program prints the lines below. Your program must print exactly these lines.

Example run

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

Write code · Easy

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

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

Write code · Medium

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

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

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.

Example run

8 <class 'int'>
8.0 <class 'float'>
1.0 <class 'float'>
4 <class 'int'>
4444 <class 'str'>

Write code · Hard

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

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.

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

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:

  1. the label Tickets sold: and the number twelve thousand five hundred, written with an underscore
  2. 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
  3. the label Income in cents: and the number of tickets multiplied by the price in cents
  4. the label Income in dollars: and the same multiplication, divided by 100
  5. the label Type of the income in dollars: and the type of the calculation from line 4
  6. 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