Part 3: Python Programming
5. Input & Output & Formatting
Input & Output & Formatting
Programs become interactive when they can talk to the user. In this chapter you will read what someone types, convert it to the right type, and control exactly how your output looks.
Reading input with input()
The input() function pauses your program, shows an optional prompt, waits for the user to type something and press Enter, then hands back what they typed as a string:
Converting input to numbers
Because input() always returns a string, you must convert it before doing arithmetic. Use int() for whole numbers and float() for decimals. Forgetting this is one of the most common beginner mistakes:
If we had skipped int(), then age + 10 would have tried to add the number 10 to a string and raised a TypeError. You can also combine the two calls on one line: age = int(input("Your age? ")).
Controlling print() with sep and end
The print() function can take several values separated by commas. By default it joins them with a space and adds a newline at the end. Two keyword arguments change that behaviour:
sepsets what goes between the values.endsets what goes after the last value instead of a newline.
Because the second print ended with "..." instead of a newline, the word "done" appeared on the same line.
Formatting numbers with f-strings
f-strings can also format values. After the expression, add a colon and a format specification. This is invaluable for money, percentages, and tidy tables:
Here .2f means "a float with two decimal places," .1% means "a percentage with one decimal place" (it multiplies by 100 and adds the sign), and the number 5 sets a minimum width so values line up in columns. The < aligns to the left.
A small interactive program
Putting it together, here is a program that asks for two numbers and reports their sum neatly:
You now have the tools to build friendly, interactive programs. Always remember the golden rule of input: convert the string to the number type you need before calculating with it.