Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 6

Input and Type Conversion

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

0 of 0 done

6.1 Asking the user: input()

Here is a program that talks back:

name = input("What is your name? ")
print("Hello,", name)

Output

What is your name? Maya
Hello, Maya

Run it yourself and type any name. The same program now gives a different result for every person who runs it. That is the whole point of input.

What happens, step by step

input is a function, just like print. One line of code does four things:

Step What Python does
1 Shows the text inside the brackets, called the prompt: What is your name?
2 Stops and waits. Nothing else in the program runs while it waits.
3 The user types something and presses Enter.
4 input gives back what was typed, as a string, and the program carries on.

Step 4 is the important one. input("...") is an expression: it has a value, and that value is whatever the user typed. The name = in front catches that value and gives it a name, exactly like any assignment from Chapter 3. If you forget to catch it, the reply is thrown away:

input("What is your name? ")
print("Hello, whoever you are")

Output

What is your name? Maya
Hello, whoever you are

The user typed Maya, but the program never stored it anywhere.

Writing a good prompt

The prompt is shown exactly as you write it, and the cursor sits right after it. That is why the examples end the prompt with a space: without one, the reply is glued to the question.

city = input("Which city?")
print("You chose", city)

Output

Which city?Tokyo
You chose Tokyo

Which city?Tokyo looks cramped. End every prompt with a space, or with a colon and a space: "Which city? " or "City: ".

The prompt is optional. input() with empty brackets shows nothing and simply waits, which confuses the person using your program: they see a blinking cursor and no question. Always say what you want.

Quick check

What does this program show, and what is stored in colour, if the user types red and presses Enter? colour = input("Colour: ")

Show the answer

Answer: the screen shows Colour: red. The name colour now refers to the string "red". The Enter key is not part of it.

Practice 6.1

Multiple choice

The user types Maya and presses Enter. What does the program show on the line after the question?

input("Your name: ")
print("Done")
Choose one answer

Put the lines in order

Put the lines in order. The program asks for the name first and for the city second, then prints one line.

With the replies Leo then Tokyo, the program in the right order prints:

Target

Leo lives in Tokyo
  1. name = input("Your name: ")
  2. print(name, "lives in", city)
  3. city = input("Your city: ")

6.2 input() always gives you text

This is the single most important fact in the chapter:

input() always gives back a str. Always. Even when the user types digits.

You can prove it with type():

age = input("Your age: ")
print(age)
print(type(age))

Output

Your age: 25
25
<class 'str'>

The user typed 25, and print shows 25, so it looks like a number. But the type is str. What you have is the two characters "2" and "5", not the number twenty-five. Python does not guess what the user meant. It hands you exactly the characters that were typed and leaves the decision to you.

Bug 1: the program crashes

Try to do arithmetic with that text and Python refuses, with the TypeError you met in Chapter 2:

age = input("Your age: ")
print("Next year you will be", age + 1)

Output

Your age: 25
Traceback (most recent call last):
  File "age.py", line 2, in <module>
    print("Next year you will be", age + 1)
                                   ~~~~^~~
TypeError: can only concatenate str (not "int") to str

Read the last line: Python sees text + number. With text on the left, + means "join", and it can only join text to text.

Bug 2: the program gives a wrong answer

This one is worse, because there is no error message at all:

first = input("First number: ")
second = input("Second number: ")
print("Total:", first + second)

Output

First number: 5
Second number: 3
Total: 53

Five plus three is not fifty-three. But first is "5" and second is "3", and + between two strings joins them (Chapter 4): "5" + "3" is "53". The program runs happily and prints nonsense.

Multiplying gives a different surprise:

count = input("How many? ")
print(count * 3)

Output

How many? 5
555

"5" * 3 repeats the text three times. Again: no error, wrong answer.

The cure for both bugs is the same: convert the text to a number before doing maths with it.

Quick check

The user types 10 and then 20. What does this print? print(input("x: ") + input("y: "))

Show the answer

Answer: 1020. Both replies are strings, and + joins strings.

Practice 6.2

Predict the output

The user types 7.

Type only the lines that print() shows, not the questions and the replies.

reply = input("Number: ")
print(reply * 2)
print(reply + reply + "1")

Multiple choice

The user types 20. What happens?

price = input("Price: ")
print(price + 5)
Choose one answer

6.3 Text to whole number: int()

int() takes a string that looks like a whole number and gives back a real int:

text = "25"
number = int(text)
print(number + 1)
print(type(text), type(number))

Output

26
<class 'str'> <class 'int'>

Notice that text itself has not changed. int(text) builds a new value, an integer, and leaves the string alone. Converting never alters the original; it makes something new from it.

Now the age program works:

age = int(input("Your age: "))
print("Next year you will be", age + 1)

Output

Your age: 25
Next year you will be 26

Reading from the inside out

int(input("Your age: ")) has one function call inside another. Python always works out the innermost brackets first, just like in arithmetic:

age = int( input("Your age: ") )
           └───────┬─────────┘
       1. ask, wait, get  "25"      (a str)
      └──────────┬───────────────┘
       2. int("25")  gives  25      (an int)
└─┬─┘
 3. the name age now refers to 25

If that feels like too much in one line, split it. These two versions do exactly the same thing:

reply = input("Your age: ")     # reply is "25"
age = int(reply)                # age is 25

Use the two-line form whenever it makes the program easier for you to read. Short is not the same as good.

What int() accepts

int() is strict, but it does allow a few reasonable things:

print(int("42"))
print(int("  42  "))      # spaces around the number are ignored
print(int("-7"))          # a minus sign
print(int("+7"))          # a plus sign
print(int("007"))         # leading zeros are fine in text
print(int("1_000_000"))   # underscores, like in Chapter 2

Output

42
42
-7
7
7
1000000

What int() refuses

Anything else is rejected with a ValueError. The value is the right type (a string) but its contents make no sense as a whole number:

print(int("3.5"))

Output

Traceback (most recent call last):
  File "convert.py", line 1, in <module>
    print(int("3.5"))
          ~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.5'

The message quotes the exact text Python choked on, inside quote marks. That is very useful: when the quotes show something unexpected, such as '' or ' 12a', you can see immediately what the user really typed. All of these fail the same way:

Call Why it fails
int("3.5") a decimal point is not allowed in a whole number
int("twelve") words are not digits
int("1,000") commas are not allowed (use 1_000 or remove them)
int("12 34") a space in the middle
int("$20") a currency sign
int("") an empty string: the user just pressed Enter

Quick check

Which of these work, and what do they give? int(" 8 "), int("8.0"), int("-0"), int("eight")

Show the answer

Answer: int(" 8 ") gives 8 and int("-0") gives 0. The other two raise ValueError: "8.0" has a decimal point, and "eight" is a word.

Practice 6.3

Fill in the blank

Fill in the blank so that the program can subtract.

pages = (input("Pages read today: "))
print("Pages left:", 300 - pages)

With the reply 120, the finished program prints:

Target

Pages left: 180

Multiple choice

Three of these calls work. Which one stops with a ValueError?

Choose one answer

6.4 Text to decimal number: float()

When the value can have a fractional part (a price, a height, a temperature), use float():

price = float(input("Price in dollars: "))
print("With tax:", round(price * 1.2, 2))

Output

Price in dollars: 19.99
With tax: 23.99

float() is more relaxed than int() about what it accepts:

print(float("3.5"))
print(float("7"))        # no decimal point needed
print(float(".5"))       # no leading zero needed
print(float("  2.50 "))  # spaces around are ignored
print(float("1e3"))      # scientific notation, from Chapter 2
print(float("-0.25"))

Output

3.5
7.0
0.5
2.5
1000.0
-0.25

Whatever goes in, a float comes out: float("7") is 7.0, not 7.

It still refuses text that is not a number, with a slightly different message:

print(float("3,5"))

Output

Traceback (most recent call last):
  File "convert.py", line 1, in <module>
    print(float("3,5"))
          ~~~~~^^^^^^^
ValueError: could not convert string to float: '3,5'

int() or float()?

Choose by asking what the value means, not what the user happens to type:

The value is... Use Examples
a count of whole things int() people, items, pages, a year, an age in years
a measurement or an amount float() height, weight, price, temperature, distance

If you use int() for a price, a user who types 4.50 crashes your program. If you use float() for a number of tickets, you may end up selling 2.5 tickets.

Practice 6.4

Predict the output

No input this time. What does it print?

print(float("8"))
print(float(".25") * 4)
print(float("1e2"))

Fix the bug

This program works for 60 but crashes when the user types 72.5. Fix it so that decimal weights work too.

With the reply 72.5, the program prints the lines below. Your program must print exactly these lines.

Example run

On the Moon: 12.0

6.5 Numbers to text: str()

Conversion works in the other direction too. str() turns any value into text:

print(str(42))
print(str(3.14))
print(str(True))
print(str(None))
print(type(str(42)))

Output

42
3.14
True
None
<class 'str'>

When do you need it? Whenever you want to join a number onto text with +:

age = 25
message = "You are " + str(age) + " years old."
print(message)

Output

You are 25 years old.

Without the str(), this is the TypeError from section 6.2. Remember from Chapter 1 that print with commas does this conversion for you and adds spaces: print("You are", age, "years old."). So you need str() mostly when you are building a string to keep, not just printing.

str() is also the way to treat a number as a row of digits. How many digits does 2 to the power 100 have?

big = 2 ** 100
print(big)
print(len(str(big)))

Output

1267650600228229401496703205376
31

A number has no "length", but its text form does. len() counts characters, and you will meet it properly in → Chapter 7.

Quick check

What do these give? str(5) + str(5) and int(str(5) + str(5)) + 1

Show the answer

Answer: "55" (two strings joined), and then 56: the text "55" is converted to the number 55, and 1 is added.

Practice 6.5

Fill in the blank

Fill in the blank so that the number can be joined to the text.

floor = 12
label = "Floor " + 
print(label)

The finished program prints:

Target

Floor 12

Predict the output

What does it print?

print(len(str(2 ** 10)))
print(str(7) * 3)
print(str(1.50))

6.6 Anything to true or false: bool()

You met bool() in Chapter 5: it tells you whether a value is truthy or falsy. It is a conversion like the others, and it has one trap that catches everybody once.

print(bool("yes"))
print(bool("no"))
print(bool("False"))
print(bool(""))

Output

True
True
True
False

bool() does not read the text. It only asks: is this string empty? Every non-empty string is truthy, including "no", "False" and "0". So this does not work:

wants_receipt = bool(input("Do you want a receipt? "))
print(wants_receipt)

Output

Do you want a receipt? no
True

The user said no, and the program heard yes. To turn a typed answer into a Boolean, compare it with the answer you are looking for:

reply = input("Do you want a receipt? ")
wants_receipt = reply == "yes"
print(wants_receipt)

Output

Do you want a receipt? no
False

reply == "yes" is a comparison, so its value is True or False, and that is what gets stored. (Users also type Yes, YES and yes with a space. Section 6.11 deals with that.)

Practice 6.6

Multiple choice

For which reply does this program print False?

reply = input("Send the email? ")
print(bool(reply))
Choose one answer

Fix the bug

This should print True only when the user types yes. Now it prints True for no too. Fix it.

With the reply no, the program prints the lines below. Your program must print exactly these lines.

Example run

Gift wrap: False

6.7 Converting between number types

int(), float() and str() are not only for strings. They convert from any type that makes sense.

int to float: nothing is lost

print(float(7))
print(float(-2))

Output

7.0
-2.0

float to int: the fraction is cut off

print(int(3.99))
print(int(3.01))
print(int(-3.99))

Output

3
3
-3

int() does not round. It throws away everything after the decimal point. Programmers call this truncating, which means cutting short. 3.99 becomes 3, and -3.99 becomes -3: the cut is always towards zero.

That gives you three different ways to turn a float into a whole number, and they do not agree:

print(int(2.7), round(2.7), 2.7 // 1)
print(int(-2.7), round(-2.7), -2.7 // 1)

Output

2 3 2.0
-2 -3 -3.0
Tool What it does 2.7 −2.7
int(x) cuts towards zero 2 −2
round(x) goes to the nearest whole number (Chapter 4) 3 −3
x // 1 goes down, towards minus infinity (Chapter 4) 2.0 −3.0

Pick the one that matches what you mean. For money and marks, you nearly always mean round.

Text with a decimal point to int: go in two steps

int("3.7") fails, as you saw. If you really want a whole number from that text, convert to a float first and then cut or round:

text = "3.7"
print(int(float(text)))
print(round(float(text)))

Output

3
4

bool and numbers

Because True is 1 and False is 0 (Chapter 5), these conversions work too:

print(int(True), int(False))
print(float(True))
print(bool(1), bool(0), bool(-5), bool(0.0))

Output

1 0
1.0
True False True False

But the text "True" is not a number, so int("True") is a ValueError.

Conversions that cannot work

print(int(float("inf")))

Output

Traceback (most recent call last):
  File "convert.py", line 1, in <module>
    print(int(float("inf")))
          ~~~^^^^^^^^^^^^^^
OverflowError: cannot convert float infinity to integer

Infinity is not a whole number, so there is nothing to give back. And None cannot be converted to any number: int(None) is a TypeError, because "no value" has no numeric meaning.

Quick check

A shop needs whole boxes to hold total / 12 eggs. For 30 eggs, what do int(30 / 12) and round(30 / 12) give, and is either one the right number of boxes?

Show the answer

Answer: 30 / 12 is 2.5. int gives 2. round also gives 2, because Python rounds a half to the nearest even number (Chapter 4). Neither is right: you need 3 boxes. Rounding up is done with math.ceil → Chapter 17, or with the trick -(-30 // 12).

Practice 6.7

Predict the output

What does it print?

print(int(9.99), round(9.99))
print(int(-0.5), round(2.5))
print(float(3) / 2)

Write code

Cut and round. Ask for one decimal number. Print two lines: first the number cut to a whole number, then the number rounded to the nearest whole number.

With the reply 7.8, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

7
8

6.8 Reading other number bases

In Chapter 2 you wrote integers in binary (0b101), octal (0o17) and hexadecimal (0xff). int() can read those from text if you tell it the base as a second argument:

print(int("101", 2))      # binary
print(int("17", 8))       # octal
print(int("ff", 16))      # hexadecimal
print(int("FF", 16))      # capitals work too
print(int("z", 36))       # base 36 uses 0-9 and then all 26 letters

Output

5
15
255
255
35

Going the other way, bin(), oct() and hex() give the text form of an integer in that base:

print(bin(5), oct(15), hex(255))
print(type(hex(255)))

Output

0b101 0o17 0xff
<class 'str'>

Now the "base 10" in the ValueError message makes sense: with no second argument, int() assumes decimal, where the only legal digits are 0 to 9.

Practice 6.8

Multiple choice

What does int("20", 8) give?

Choose one answer

Fill in the blank

Fill in the base so that the binary text is read correctly.

print(int("1010", ))

The finished program prints:

Target

10

6.9 What Python converts for you, and what it never does

Sometimes Python converts a value without being asked. This is called implicit conversion (implicit means "not stated"). When you write the conversion yourself, as in int("5"), that is explicit conversion. Programmers also call explicit conversion casting.

Python's implicit conversions are deliberately few:

Situation Python converts... Example Result
int mixed with float the int to a float 2 + 0.5 2.5
bool used in arithmetic the bool to 1 or 0 True + 4 5
any value where true/false is needed to its truthiness 0 or "x" "x"
any value handed to print to text for display print(42) 42

All four are safe: no information is lost and there is only one sensible answer.

Python never converts between text and numbers on its own. Is "5" + 3 supposed to be 8 or "53"? Both answers are reasonable, so Python refuses to pick one and raises a TypeError. You have to say which one you mean:

print(int("5") + 3)
print("5" + str(3))

Output

8
53

This is a design choice. Some languages do guess (in JavaScript, "5" + 3 is "53" but "5" - 3 is 2), and those guesses are a well-known source of bugs. Python's motto, from a short poem about its design that you can read by typing import this in the shell, is: explicit is better than implicit.

Practice 6.9

Multiple choice

Three of these lines run. Which one stops with an error?

Choose one answer

Predict the output

What does it print?

print(True + True + 0.5)
print(int("4") + 4)
print("4" + str(4))

6.10 Several values on one line

Asking three separate questions for three numbers is tedious. Users often prefer to type everything on one line: 3 4 5. A string method called split cuts a line of text into pieces wherever there are spaces → Chapter 9, and multiple assignment from Chapter 3 gives each piece a name:

width, height = input("Width and height: ").split()
print(width)
print(height)
print("Area:", int(width) * int(height))

Output

Width and height: 3 4
3
4
Area: 12

Follow it from the inside out: input(...) gives "3 4"; .split() cuts that into the two strings "3" and "4"; the two names on the left each take one. They are still strings, so each one is converted with int() before the multiplication.

The number of names must match the number of pieces. If the user types three values and you provided two names, Python reports a ValueError saying there were too many values to unpack.

Practice 6.10

Fill in the blank

The user types 2 30 on one line. Fill in the method that cuts the line into two pieces.

This uses the string method split(), which is taught in Chapter 9.

hours, minutes = input("Hours and minutes: ").()
print(int(hours) * 60 + int(minutes))

With the reply 2 30, the finished program prints:

Target

150

6.11 Cleaning up what the user typed

People are not careful typists. They add spaces, and they use capitals whenever they feel like it. A comparison like reply == "yes" fails for "Yes", "YES" and "yes ".

Two string methods fix nearly all of this. strip() removes spaces from both ends, and lower() turns every letter into lowercase → Chapter 9:

reply = input("Continue? ").strip().lower()
print(reply == "yes")

Output

Continue?   YES
True

Read the first line left to right: get the reply, strip the spaces, make it lowercase, and only then store it. From that point on, the program only ever sees the clean form "yes".

For numbers you do not need strip(), because int() and float() already ignore spaces at the ends.

Practice 6.11

Put the lines in order

Put the lines in order: get the reply, clean it, then compare it.

This uses the string methods strip() and lower(), which is taught in Chapter 9.

With the reply RED , the program in the right order prints:

Target

True
  1. print(clean == "red")
  2. reply = input("Colour: ")
  3. clean = reply.strip().lower()

6.12 Looking before you convert

What should a program do when the user types abc where a number is expected? Right now, it crashes with a ValueError. There are two ways to do better, and both need tools from later chapters, so this is only a first look.

Check first. The string method isdigit() answers the question "is this text made only of digits?" with a Boolean:

print("123".isdigit())
print("12a".isdigit())
print("".isdigit())
print("-5".isdigit())
print("3.5".isdigit())

Output

True
False
False
False
False

Look at the last two. A minus sign and a decimal point are not digits, so isdigit() says False for perfectly good numbers like -5 and 3.5. It is only a rough check, useful for things that must be plain digits, such as a quantity or a PIN.

Try, and recover if it fails. The professional way is to attempt the conversion and catch the error if it happens, using try and except → Chapter 10. Combined with a loop → Chapter 13, that lets a program keep asking until it gets a usable answer.

Until then, your programs will assume a cooperative user. That is fine for learning. Just know that real programs never trust input.

Practice 6.12

Predict the output

What does it print?

This uses the string method isdigit(), which is taught in Chapter 9.

print("2024".isdigit())
print("20.5".isdigit())
print("-3".isdigit())

6.13 Built-in functions

print, input, int, float, str, bool, type, len... You have been collecting these since Chapter 1. They are called built-in functions: they are part of Python itself and are always available, with nothing to install or switch on. Python has about 70 of them.

Every function call follows the same shape:

        name      arguments (what you hand over)
         │            │
result = round(  3.14159, 2  )
  │
  └── the value the function gives back  (3.14)

A function takes zero or more arguments and gives back one value. Programmers say it returns a value. Because a call has a value, you can use it anywhere a value is allowed: store it, print it, do maths with it, or hand it straight to another function.

Here are the built-ins you can use with what you know so far:

Function What it gives back Example Result
print(...) nothing useful (None); it shows text print("hi") shows hi
input(prompt) the line the user typed, as a str input("? ") a str
type(x) the type of x type(2.5) <class 'float'>
int(x), float(x), str(x), bool(x) x converted to that type int("7") 7
len(s) how many characters are in s len("hello") 5
abs(x) the size of x, without its sign abs(-4) 4
round(x, n) x rounded to n decimal places round(2.567, 1) 2.6
pow(x, y) x to the power y pow(2, 5) 32
divmod(x, y) the quotient and remainder together divmod(17, 5) (3, 2)
min(...), max(...) the smallest or largest argument max(3, 9, 4) 9
bin(n), oct(n), hex(n) n written in that base, as text hex(255) '0xff'
id(x) the identity number of the object (Chapter 3) id(x) a large number

min and max also work on strings, using the dictionary order from Chapter 5:

print(min(4, 9, 2), max(4, 9, 2))
print(max("pear", "plum", "peach"))
print(divmod(17, 5))

Output

2 9
plum
(3, 2)

Combining functions

Since a call is a value, calls can be nested. Read them from the inside out, one layer at a time:

print(round(abs(float("-3.14159")), 2))

Output

3.14

float("-3.14159") gives -3.14159; abs of that gives 3.14159; round(..., 2) gives 3.14; print shows it. Three layers is about the limit of what is comfortable to read. Past that, use variables for the steps in between.

Finding out what a function does

You do not have to memorise all 70. Python carries its own manual. In the shell, help shows the documentation for any function:

Terminal

>>> help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    ...

In VS Code, hover the mouse over a function's name to see the same text. The complete list is in the official documentation, under "Built-in Functions". You will meet more of them in almost every chapter, and from → Chapter 19 you will write functions of your own.

Practice 6.13

Predict the output

What does it print?

print(abs(-7) + max(2, 9))
print(round(pow(2, 5) / 3, 1))
print(min("kiwi", "fig", "plum"))

Write code

Largest and smallest. Ask for three whole numbers, with three questions. Print the largest number first, then the smallest.

With the replies 4 then 9 then 2, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

9
2

6.14 Common mistakes

The mistake What you see The fix
Doing maths with a reply that is still text TypeError, or answers like 53 and 555 Convert first: int(input(...))
int("4.5") for a decimal number ValueError: invalid literal for int() Use float(), or int(float(text))
Expecting int(3.9) to give 4 3 Use round(3.9)
bool(reply) to read yes or no True for every answer except an empty one Compare: reply == "yes"
"Total: " + total with a number TypeError: can only concatenate str "Total: " + str(total), or use commas in print
No space at the end of the prompt The reply is glued to the question End the prompt with a space
Not storing the reply The value is lost name = input(...)
Converting again and again Cluttered code such as int(age) + int(age) Convert once, when the value arrives
Naming a variable input or int TypeError: 'str' object is not callable later on Pick another name

Practice 6.14

Fix the bug

This program crashes on its last line. Fix it so that it prints Total: 13.5.

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

Example run

Total: 13.5

6.15 Putting it together

6.16 How input and conversion work

+ 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 type of value does input() give back when the user types 42? When they type 3.5? When they just press Enter?

Show the answer

A str every time: "42", "3.5" and "" (the empty string).

Check yourself

Why does the prompt usually end with a space?

Show the answer

The user's typing starts immediately after the prompt. Without the space, the reply is glued to the question.

Check yourself

Explain in your own words why input("x: ") + 1 is an error.

Show the answer

input gives back a string. With a string on the left, + means "join", and Python can only join a string to another string, not to the integer 1.

Check yourself

What is the difference between int("7") and float("7")? Print both to check.

Show the answer

Both convert text to a number, but int("7") gives the integer 7 and float("7") gives the float 7.0.

Check yourself

Name three strings that float() accepts but int() refuses.

Show the answer

Any text with a decimal point or an exponent, for example "3.5", ".5" and "1e3". (Also "inf" and "nan".)

Check yourself

What do int(9.99), int(-9.99) and round(9.99) give?

Show the answer

9, -9 and 10. int cuts towards zero; round goes to the nearest whole number.

Check yourself

Why is bool(input("Yes or no? ")) almost always True? When is it False?

Show the answer

bool of a string only checks whether it is empty. Any reply with at least one character is truthy, including "no". It is False only when the user presses Enter without typing anything.

Check yourself

Give one conversion Python does for you, and one it never does.

Show the answer

Done for you: int to float in mixed arithmetic (2 + 0.5), or bool to int. Never done: text to number or number to text ("5" + 3 is an error).

Check yourself

In int(input("Age: ")), which function runs first, and what does it hand to the other one?

Show the answer

input runs first, because it is the innermost call. It hands the typed text, a str, to int.

Check yourself

What does ValueError: invalid literal for int() with base 10: '' tell you the user did?

Show the answer

The text between the quotes is empty, so the user pressed Enter without typing anything.

Predict the output

Predict the output

The user types 4 and then 6.

Type only the lines that print() shows, not the questions and the replies.

first = input("First: ")
second = input("Second: ")
print(first + second)
print(int(first) + int(second))
print(first * int(second))

Predict the output

print(int("12") + float("0.5"))
print(str(12) + str(0.5))
print(int(7.9) + int(-7.9))
print(int("  30 ") // 4)

Predict the output

print(bool("0"), bool(0), bool(int("0")), bool(str(0)))
print(int(True) + int("1") + int(1.9))

Predict the output

print(int("11", 2), int("11", 8), int("11", 16), int("11"))
print(str(int("0042")) + "!")
print(len(str(10 ** 6)))

Fix the bug

Fix the bug

This should print the user's age in months. For 10 it prints 101010101010101010101010.

With the reply 10, the program prints the lines below. Your program must print exactly these lines.

Example run

Age in months: 120

Fix the bug

This crashes when the user types 4.5.

With the reply 4.5, the program prints the lines below. Your program must print exactly these lines.

Example run

Pay: 90.0

Fix the bug

This should print True only when the user wants a bag. It prints True even when they type no.

With the reply no, the program prints the lines below. Your program must print exactly these lines.

Example run

False

Fix the bug

This crashes on its last line.

With the reply 88, the program prints the lines below. Your program must print exactly these lines.

Example run

Your score is 88 points

Fix the bug

This should print the average of two marks. For 80 and 90 it prints 4045.0.

With the replies 80 then 90, the program prints the lines below. Your program must print exactly these lines.

Example run

85.0

Coding problems

Write code · Easy

Greeting card. Ask for a name and a city, and print a line such as Maya from Tokyo, welcome! Do it once with commas in print and once by building one string with +.

Ask for the name first, then the city. Print the line two times: once with commas in print, once built with +.

With the replies Maya then Tokyo, the program prints the lines below. Your program must print exactly these lines.

Example run

Maya from Tokyo, welcome!
Maya from Tokyo, welcome!

Write code · Easy

Years to 100. Ask for the user's age and print how many years are left until they are 100.

With the reply 19, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

81

Write code · Easy

Rectangle. Ask for a width and a height as decimal numbers, and print the area and the perimeter.

Ask for the width first, then the height. Print the area first, then the perimeter.

With the replies 4.5 then 2, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Area: 9.0
Perimeter: 13.0

Write code · Medium

Temperature converter. Ask for a temperature in Celsius and print it in Fahrenheit, rounded to one decimal place. The formula is F = C × 9 / 5 + 32.

With the reply 36.6, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

In Fahrenheit: 97.9

Write code · Medium

Seconds to clock time. Ask for a whole number of seconds and print it as hours, minutes and seconds. For 3725 the answer is 1 2 5.

With the reply 3725, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

1 2 5

Write code · Medium

Two on one line. Ask for two whole numbers on one line, separated by a space, and print their sum, their product, and which is larger using max.

Print the sum first, then the product, then the larger number.

With the reply 12 7, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Sum: 19
Product: 84
Larger: 12

Write code · Hard

Digit facts. Ask for a whole number. Print how many digits it has, its first digit and its last digit, without using indexing (that is Chapter 8).

Print the number of digits first, then the first digit, then the last digit.

With the reply 58213, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Digits: 5
First digit: 5
Last digit: 3

Write code · Hard

Change machine. Ask for a price and the amount paid, both in dollars with decimals. Print the change as a number of whole dollars and a number of cents. For a price of 4.35 paid with 10 it should print 5 and 65.

Ask for the price first, then the amount paid. Print the whole dollars first, then the cents.

With the replies 4.35 then 10, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Dollars: 5
Cents: 65

Write code · Hard

Base translator. Ask for a number written in hexadecimal, such as ff, and print it in decimal, in binary and in octal.

Print three lines with these labels: Decimal:, Binary: and Octal:.

With the reply ff, the program prints the lines below. Your program must print exactly these lines.

Example run

Decimal: 255
Binary: 0b11111111
Octal: 0o377

Chapter project: Trip fuel budget

Project

Plan a road trip. Friends share the cost of fuel for a trip. Write a program that asks four questions, in this order:

  1. the distance in km (can be a decimal number)
  2. how many litres of fuel the car uses for 100 km (can be a decimal number)
  3. the price of one litre in dollars (can be a decimal number)
  4. the number of people (a whole number)

Then print three lines: the litres of fuel needed, rounded to 1 decimal place; the cost of the trip, rounded to 2 decimal places; and what each person pays, rounded to 2 decimal places.

Before you write code, decide the type of every input by asking what it means, as section 6.15 did. Do the calculations with the full values, and round only when you print.

With the replies 250 then 6.4 then 1.85 then 4, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Fuel needed: 16.0
Trip cost: 29.6
Each person pays: 7.4