SchoolWhool
Quizzes and saved progress, freeSign in freeSign in

Python 1.5Free video11 minLesson 5 of 6 in Module 1

Input, Output and Formatting

Read input and print results readably.

Free sample. Everything in this module opens with a free account.

Watch or read the lesson: Input, Output and Formatting

01Output with print()

So far, almost every value you have worked with has been written directly into your Python code. But what if you want someone else to enter those values?

Imagine you are out for dinner with a few friends. The bill arrives, and now you need to work out how much each person should pay, including the tip. A small Python program can do exactly that. It asks for the bill amount, the tip percentage and the number of people. Then it calculates how much each person owes and displays the result with two decimal places. Here is one run of it, where the person at the keyboard typed 84.60, 15 and 3:

Bill amount: 84.60
Tip %: 15
People: 3
Each person pays $32.43

By the end of this lesson, you will be able to build this program yourself. To get there, you need three things:

  1. How to display output using print().
  2. How to format that output using f-strings.
  3. How to get information from the user using input().

Several arguments

You have already used print. This time, pass it more than one value. Say you want to display the word Total, followed by the number 20.75. You can pass both values to print(), separated by a comma:

print("Total", 20.75)
Total 20.75

Notice the space between Total and 20.75. You did not write that space anywhere. So where did it come from?

sep: the separator

print() has an optional argument called sep, short for separator. It controls what appears between the values you pass to print(), and by default the separator is a single space. That is where the space came from.

But you can change it. Suppose you want to display a date. You have the day, 12, the month, 5, and the year, 2026. If you pass these values to print and set sep to a forward slash, you get a proper date format:

print(12, 5, 2026, sep="/")
12/5/2026

Instead of spaces, Python puts a forward slash between the values.

end: what comes after the last value

There is another optional argument called end. It controls what print() writes after it has displayed the last value. By default, end is a newline character, which is why each call to print() normally starts a new line:

print("Loading")
print("Done")
Loading
Done

What if you don't want that? What if you want the next output to continue on the same line? Then you change end. If you set end to three dots, Python writes those dots after the value instead of moving to a new line, so the next print() continues right after them:

print("Loading", end="...")
print("Done")
Loading...Done

What does print return?

You know that print() displays values. But does it actually return anything? Try this:

r = print("x")
Predict first

What do you think gets stored in r? Will it be the string x, or something else? Think it through before reading on.

I have a guess. Show meHide the answer

When the cell runs, Python first displays x:

x

Now look at r:

print(r)
None

r holds None, not the string x.

Displaying a value is not returning a value

Why? Because there is a difference between displaying a value and returning a value. The print() function displays output, but its return value, the value the call hands back to the code that called it, is None. So when you assign the result of print() to r, you are actually assigning None.

That is an important distinction, and you will see it again when you start writing your own functions.

02Formatting with f-strings

Most of the time, you don't just want to print individual values. You want to put those values inside a sentence, such as:

The Pasta costs 12.5

Part of that sentence is fixed text, but the item name and the price might change. So how do you combine them?

f-strings

Python has a really convenient feature for this, called an f-string. An f-string is a formatted string literal, and it lets you insert values directly into a string. Here is how it works:

  • You write the letter f right before the opening quote.
  • Inside the string, you put Python expressions between curly braces, { and }.

When Python evaluates the f-string, it evaluates those expressions and formats their results into the surrounding text.

Suppose you have an item and a price:

item = "Pasta"
price = 12.5

Now you can write an f-string that includes both values. Put item inside one pair of curly braces and price inside another:

print(f"The {item} costs {price}")
The Pasta costs 12.5

The nice thing is that you don't have to convert the price into a string yourself first, with str(price). The f-string handles the formatting for you.

Forgetting the f

Here is a mistake that is very easy to make when you are starting out: forgetting the f. Take the exact same string, but remove the f from the beginning:

print("The {item} costs {price}")
Predict first

What do you think happens now? Think it through before reading on.

I have a guess. Show meHide the answer
The {item} costs {price}

This time, Python prints the curly braces and the names inside them, exactly as you wrote them. Without the f, it is just an ordinary string. Python does not evaluate the expressions inside the curly braces; it treats them as text. So whenever you want to insert expressions into a string this way, remember the f.

Expressions inside the braces

You are not limited to putting variable names inside the curly braces. You can put expressions there too. Suppose you want the cost of two plates of pasta. Instead of calculating the total separately, you can put price * 2 directly inside the curly braces. Python evaluates that expression and inserts the result:

print(f"The {item} costs {price * 2} for 2")
The Pasta costs 25.0 for 2

The older format method

f-strings were introduced in Python 3.6. So if you look at older Python code, you might see another way of formatting strings: the format() method. With this approach, you write placeholders using curly braces, and then call .format() with the values you want to insert. Python fills those placeholders using the arguments you provide:

print("The {} costs {}".format(item, price))
The Pasta costs 12.5

In older code you might see empty curly braces, as above, but also numbered placeholders, where the number is the position of the argument to use:

"The {1} costs {0}".format(price, item)
'The Pasta costs 12.5'

or named placeholders, filled by name:

"The {item} costs {price}".format(item=item, price=price)
'The Pasta costs 12.5'

(Those two cells show quotes around the result because the last line of the cell is a string value, and the notebook displays it as a string. print shows the text without quotes.)

It is worth recognizing .format() when you read existing code. But for most new Python code, use f-strings. They are usually easier to read, because each expression appears exactly where its value will be displayed.

Debugging with =

There is also a useful f-string feature for debugging. Suppose you have a variable called people, with the value 3. Normally, if you put people inside an f-string, you just get 3:

people = 3
print(f"{people}")
3

But what if you want to see both the variable name and its value? Add an equals sign after the expression, inside the curly braces:

print(f"{people=}")
people=3

That is especially useful when you are debugging and want to quickly inspect several variables.

03Format specifiers

Now that you know how to insert values into strings, you can take formatting a little further and control exactly how a value looks.

Think about prices. If something costs 12.5, you would normally want to display it as 12.50: two decimal places. That is where format specifiers come in. Inside an f-string, after the expression, you can add a colon followed by a format specifierKey termAfter the colon in an "f" string's braces, how a value is shown: {price:.2f}, {52000:,}, {name:<10}., which tells Python how to format that value:

f"{price:.2f}"

Here the expression is price, the colon separates it from the specifier, and the specifier is .2f.

Two decimal places with .2f

In .2f, the f means fixed-point formatting: the number is written with a fixed number of digits after the decimal point. The .2 says how many: two. So instead of 12.5, Python displays 12.50:

f"{price:.2f}"
'12.50'

What if the number has more than two decimal places? Try 3.14159:

print(f"{3.14159:.2f}")
3.14

.2f rounds the displayed result to two decimal places. So if you try 3.146 instead, the third digit rounds the second one up:

print(f"{3.146:.2f}")
3.15

Notice the word displayed. The format specifier controls the text that appears on the screen. This is really useful when displaying prices, measurements, or other numerical results, whenever the display needs a fixed precision.

04Reading input with input()

The output side is ready. Now to get the bill amount from the user, instead of writing it directly into the code.

That is what the input() function is for: it reads text entered by the user. Here is how it works:

  • You call input() and give it a prompt, the text shown to the user.
  • Python displays that prompt and waits for the user to type something.
  • Once the user presses Enter, input() returns whatever they typed, and you can store that result in a variable.

Ask the user to enter the bill amount:

bill = input("Bill amount: ")

When you run this cell, Python displays the prompt Bill amount: and waits. Type 84.60 and press Enter. The notebook shows the prompt followed by what you typed:

Bill amount: 84.60

The value is now stored in bill.

What type is bill?

Predict first

What type do you think bill is? Is it a float, because you entered a decimal number? Or is it something else? Check it with type(). Think it through before reading on.

I have a guess. Show meHide the answer
type(bill)
str

It is a string. Even though you entered 84.60, Python stored it as text. That is because input() always returns a string, even when the user types digits.

A string in a calculation

So what happens if you use that text inside a calculation? Suppose you want to add a 15 percent tip to the bill, so you try multiplying bill by 1.15:

bill * 1.15
TypeError: can't multiply sequence by non-int of type 'float'

You get an error. Python tells you that it can't multiply a sequence by a non-integer of type float. Why? Because bill is a string, as you just saw, and Python does not support multiplying a string by a float.

A string times an integer

Here is something even more interesting. Ask the user how many people are sharing the bill, and store the answer using input():

people = input("Number of people: ")

The user types 3 and presses Enter:

Number of people: 3
Predict first

Now, what happens if you multiply people by 2? Remember, people is still a string. Think it through before reading on.

I have a guess. Show meHide the answer
people * 2
'33'

You get '33', not 6. In Python, multiplying a string by an integer repeats the string, so the string "3" multiplied by 2 gives "33". Python does not raise an error here. The code runs perfectly fine; it just does not do what you intended. That makes this mistake harder to spot than the TypeError.

Converting the input

So how do you fix this? Use the conversion functions from the previous lesson on the result of input(): float() for the bill amount, and int() for the number of people. The code becomes:

bill = float(input("Bill amount: "))
bill

Typing 84.60 again gives:

Bill amount: 84.60
84.6

This time bill is the number 84.6, not the text "84.60".

Nested function calls

Notice how one function call has been placed inside another. This is called a nested function call. Here is what happens, step by step:

  1. Python evaluates the inner input() call first. The user types 84.60, and input() returns the string "84.60".
  2. That string is passed to the outer float() function.
  3. float() converts it into the floating-point number 84.6.
  4. Finally, Python binds the name bill to that float object.

You do something similar for people, except with int(), because the number of people should be a whole number. Type 3 at the prompt, then check the value and its type:

people = int(input("Number of people: "))
Number of people: 3
people, type(people)
(3, int)

people is now the integer 3, so people * 2 would give 6.

05Invalid input and ValueError

What happens if the user enters something that cannot be converted into the type you expect? You get a ValueError. It is the same conversion failure you saw with int("10p") in the previous lesson. For example, if the user types the word three where a number of people was expected, int() receives text that is not a whole number:

int("three")
ValueError: invalid literal for int() with base 10: 'three'

The conversion stops the program with that error. You will learn how to handle it without stopping the program when you cover exceptions.

06Recap and challenge

Now bring everything together. A program that reads numbers from the user works in four steps, and it is worth checking each of them in your own program:

  1. Read text with input(). Whatever the user types comes back as a string.
  2. Convert that text with float() or int(), often as a nested call such as float(input("Bill amount: ")).
  3. Compute with the converted numbers.
  4. Format the result with an f-string, using a format specifier such as .2f when the display needs two decimal places, and show it with print().

Along the way: print() separates its arguments with sep and finishes with end, and it returns None; an f-string needs its f; and .format() is the older way of doing the same job.

Your challenge

Now it is your turn. Build the bill splitter from the start of this lesson:

  1. Ask for the bill amount, the tip percentage, and the number of people.
  2. Calculate how much each person should pay.
  3. Display the result with exactly two decimal places.

If you type 84.60, 15 and 3, your program should end by showing Each person pays $32.43.

Next comes a closer look at Python's operators: the different operations Python supports, and the order in which it evaluates them.