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
inputgives 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")
Look at the first line. Is the reply stored in a variable?
The reply is thrown away, so only the print line shows something.
The answer is: Done
The reply was never stored, so the program cannot use it. Only print("Done") shows text.
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
name=input("Your name: ")
print(name,"lives in",city)
city=input("Your city: ")
A variable must get its value before a later line uses it.
Python runs the lines from top to bottom. Each input line must run before the line that uses its reply.
6.2input() 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:
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.
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
Output
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 ignoredprint(int("-7"))# a minus signprint(int("+7"))# a plus signprint(int("007"))# leading zeros are fine in textprint(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.
int() turns the text "120" into the whole number 120. After that, the subtraction works.
Multiple choice
Three of these calls work. Which one stops with a ValueError?
int() ignores spaces at the ends, and it accepts a sign and underscores.
A whole number has no decimal point.
The answer is: int("12.0")
int() refuses a decimal point, even when the part after it is zero. Use float() for that text.
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 neededprint(float(".5"))# no leading zero neededprint(float(" 2.50 "))# spaces around are ignoredprint(float("1e3"))# scientific notation, from Chapter 2print(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.
When do you need it? Whenever you want to join a number onto text with +:
age=25message="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**100print(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=12label="Floor "+print(label)
The finished program prints:
Target
Floor 12
+ joins text to text only. floor is a number.
Which function turns any value into text?
floor=12label="Floor "+str(floor)print(label)
str(floor) builds the text "12". Two pieces of text can be joined with +.
2 ** 10 is 1024. len() counts the characters of its text form.
Text times 3 repeats the text. A float does not keep a zero at the end.
It prints
4
777
1.5
str() gives the text form of a value. Text can be counted with len() and repeated with *.
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.
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))
bool() does not read the text.
Only one string is falsy: the empty string.
The answer is: The user presses Enter and types nothing
bool() of a string is False only for the empty string. Every other reply is truthy, even no.
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
Output
bool(reply) is True for every reply that is not empty.
A comparison with == gives True or False. Store that.
To turn a typed reply into a Boolean, compare it with the text you are looking for.
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:
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).
int() cuts towards zero. round() goes to the nearest whole number.
A half is rounded to the nearest even number.
It prints
9 10
0 2
1.5
int() cuts the fraction off, round() goes to the nearest whole number, and a half goes to the even neighbour.
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
Output
Convert the reply with float() first.
int() cuts the fraction off. round() goes to the nearest whole number.
The same float gives two different whole numbers: int() cuts towards zero and round() goes to the nearest.
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))# binaryprint(int("17",8))# octalprint(int("ff",16))# hexadecimalprint(int("FF",16))# capitals work tooprint(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:
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?
The second argument is the base. Here the text is read in base 8.
In base 8, 20 means two eights plus zero ones.
The answer is: 16
With base 8, the digits 2 and 0 mean two eights and zero ones, which is 16.
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
Binary is the base that has only the digits 0 and 1.
The target is 10: one eight plus one two.
print(int("1010",2))
Base 2 is binary. 1010 means one eight, zero fours, one two and zero ones.
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?
Python converts int to float, and bool to int, on its own.
Python never converts between text and numbers on its own. Text times a number is allowed: it repeats the text.
The answer is: print("5" + 3)
"5" + 3 could mean 8 or "53", so Python refuses to guess and raises a TypeError.
True counts as 1 in arithmetic. An int mixed with a float gives a float.
The second line adds two numbers. The third line joins two pieces of text.
It prints
2.5
8
44
The first line uses implicit conversion. The other two lines use explicit conversion, and each one says which meaning of + is wanted.
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
This section showed one method that cuts text wherever there are spaces.
Its name is the word for cutting something into parts.
hours,minutes=input("Hours and minutes: ").split()print(int(hours)*60+int(minutes))
split() cuts "2 30" into "2" and "30". Both are still text, so each one is converted with int().
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:
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
print(clean=="red")
reply=input("Colour: ")
clean=reply.strip().lower()
A name must exist before another line uses it.
clean is made from reply, and the last line uses clean.
Clean the reply as soon as it arrives. After that, the comparison only ever sees the clean form.
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:
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.
isdigit() is only a rough check. It says False for good numbers that have a sign or a decimal point.
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:
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.
Convert at the door. max and min on text use dictionary order, which gives wrong results for numbers.
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
Output
Read the last line of the error message. Which two types does + get?
Turn the number into text with str(), or let print do the work with a comma.
total=3*4.5print("Total: "+str(total))
+ joins text to text only. str(total) makes the text, or a comma in print does the conversion for you.
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.
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!
Output
With commas, print puts a space between the parts. That gives a space before the comma unless you join the city and ", welcome!" with +.
For the second line, write every space yourself: name + " from " + city + ", welcome!".
name=input("Your name: ")city=input("Your city: ")print(name,"from",city+", welcome!")print(name+" from "+city+", welcome!")
name=input("Your name: ")city=input("Your city: ")print(name,"from",city+", welcome!")print(name+" from "+city+", welcome!")
Output
Your name: Maya
Your city: Tokyo
Maya from Tokyo, welcome!
Maya from Tokyo, welcome!
In the first print, city + ", welcome!" is joined with + so that there is no space before the comma.
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
Output
The reply is text. Convert it with int() before you subtract.
The number of years left is 100 minus the reply.
years=int(input("Your age: "))print(100-years)
age=int(input("Your age: "))print("Years until you are 100:",100-age)
Output
Your age: 19
Years until you are 100: 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
Output
Both values can have a fractional part, so use float().
The area is width times height. The perimeter is two times the sum of width and height.
A whole number: 58213
Digits: 5
First digit: 5
Last digit: 3
This works for positive numbers. For a negative number, str includes the minus sign, so you would use abs(number) first.
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
Output
Once both amounts are whole cents, // and % with 100 split the change into dollars and cents.
floats are approximate (Chapter 2). Convert both amounts to whole cents first, using round(... * 100), and do all the maths on integers.
Float amounts are approximate, so the safe plan is to turn both amounts into whole cents straight away and do all the maths on integers, which are exact.
round is used here, not int. In floats, 4.35 * 100 comes out as 434.99999999999994, slightly below the true value. int would cut that down to 434 and lose a cent; round gives the correct 435.
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
Output
int(text, 16) reads text written in hexadecimal.
bin() and oct() give the text form of a number in base 2 and base 8.
Plan a road trip. Friends share the cost of fuel for a trip. Write a program that asks four questions, in this order:
the distance in km (can be a decimal number)
how many litres of fuel the car uses for 100 km (can be a decimal number)
the price of one litre in dollars (can be a decimal number)
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
Output
Three inputs are measurements or amounts, so they use float(). One input is a count, so it uses int().
Litres needed = distance times litres per 100 km, divided by 100. Cost = litres times price. Each person pays cost divided by people.
Keep the full values in variables. Use round(value, 1) or round(value, 2) inside the print lines only.
distance=float(input("Distance in km: "))per_hundred=float(input("Litres per hundred km: "))price=float(input("Price of one litre: "))people=int(input("Number of people: "))litres=distance*per_hundred/100cost=litres*priceeach=cost/peopleprint("Fuel needed:",round(litres,1))print("Trip cost:",round(cost,2))print("Each person pays:",round(each,2))
The program has the shape from section 6.15: collect and convert the inputs, calculate with full values, then round only when showing the results.