Academic Block

Python Input & OutputGet Certified

What Are Input and Output?

Almost every useful program talks to its user. Output is anything the program shows, such as a message, a result, or a table. Input is anything the program receives, such as a name typed on the keyboard. In Python, the print() function handles output and the input() function handles input. Together they let you write programs that ask a question, think, and give an answer.

  • print(): displays values on the screen, and adds a new line at the end by default.
  • input(): shows an optional prompt, waits for the user, and returns what was typed as a string.
  • Escape sequences: special combinations such as \n and \t that add new lines and tabs to text.
  • f-strings: the modern way to mix variables into text and to format numbers neatly.
  • Type conversion: because input() returns text, numbers must be converted with int() or float().

Output with print()

The print() function accepts any number of values separated by commas. It converts each value to text, puts a space between them, and finishes with a new line. Two optional keyword arguments change this behaviour:

  • sep: the separator placed between values. The default is a single space.
  • end: the text printed after the last value. The default is a new line "\n".
  • Empty call: print() with no arguments prints a blank line.

Try It: print(), sep and end

Click Test My Code and read the output carefully. Then change the separator on the second line to "/" and run it again.

What this code does: It prints two words with the default separator, prints a date with a hyphen as the separator, keeps two prints on the same line by changing end, and then prints a blank line before the final message.
print("Hello", "World")
print("2026", "11", "22", sep="-")
print("Loading", end="...")
print("done")
print()
print("After a blank line")

Escape Sequences and Raw Strings

Inside a string, a backslash \ starts an escape sequence, which stands for a character that is hard to type. The most useful ones are:

  • \n starts a new line.
  • \t inserts a tab.
  • \\ prints one backslash.
  • \" and \' print a quotation mark inside a string that uses the same kind of quotes.

A raw string is written with an r before the opening quote. It treats backslashes as ordinary characters, which is handy for file paths and regular expressions.

Try It: Escape Sequences

Click Test My Code. The last line is a raw string, so its \n and \t are shown exactly as written.

What this code does: It prints text with a tab, a line break, quotation marks, an apostrophe, and backslashes. The last line uses a raw string so that no escape sequence is processed.
print("Name:\tAsha")
print("Line one\nLine two")
print("She said \"Hi\"")
print('It\'s fine')
print("C:\\Users\\Asha")
print(r"C:\new\table")

Formatted Output with f-strings

An f-string starts with the letter f before the opening quote. Anything inside curly braces { } is evaluated as Python code and inserted into the text. After a colon, you can add a format specification that controls how the value is displayed:

  • {price:.2f} shows a number with exactly 2 digits after the decimal point.
  • {price:,.2f} adds thousands separators as well.
  • {rate:.1%} multiplies by 100 and adds a percent sign.
  • {name:>8}, {name:<8} and {name:^8} right-align, left-align, and center the value in a field 8 characters wide.
  • {7:03d} pads an integer with zeros to a width of 3.

Try It: f-string Formatting

Click Test My Code. Change the numbers of decimal places, the width, or the values and run it again to see how the output reacts.

What this code does: It inserts a name into a greeting, then prints a price with two decimals, with a thousands separator, and a rate as a percentage. It aligns a name three different ways inside a field of 8 characters and pads a number with zeros.
name = "Asha"
price = 1234.5
rate = 0.075

print(f"Hello, {name}!")
print(f"Price: {price:.2f}")
print(f"Price: {price:,.2f}")
print(f"Rate: {rate:.1%}")
print(f"[{name:>8}] [{name:<8}] [{name:^8}]")
print(f"{7:03d}")

Other Ways to Format: format() and %

Before f-strings were introduced in Python 3.6, programmers used two older styles. You will meet them in existing code, so it is worth recognizing them. The str.format() method uses {} placeholders that are filled in order, by position number, or by name. The % operator is the oldest style and uses codes such as %s for text, %d for integers, and %.2f for decimals. For new code, f-strings are clearer and are the recommended choice.

Try It: format() and the % Operator

Click Test My Code and compare the five lines. Notice how the positions in the second line change the order of the values.

What this code does: It builds text with the format() method using automatic placeholders, numbered placeholders, and named placeholders, and then builds text with the older % operator.
item = "pen"
qty = 3
print("{} x {}".format(qty, item))
print("{1} x {0}".format(item, qty))
print("{name} costs {cost}".format(name=item, cost=1.5))
print("%s x %d" % (item, qty))
print("%.1f" % 3.14159)

Input with input()

The input() function pauses the program and waits until the user types a line. You can pass a prompt, a message that tells the user what to type. The function returns the text that was typed, without the final new line. The result is always a str, so convert it with int() or float() when you need a number.

Note for this tutorial: the code runner on this site does not pause for live typing. It reads every response from the Program Input box before the program starts, one line for each input() call. If you provide fewer lines than the program asks for, Python stops with an EOFError. In a normal Python program on your own computer, the same code waits for you to type.

Try It: Asking Questions

The Program Input box is already filled with Asha on the first line and 20 on the second. Click Run Code straight away, then try other answers.

What this code does: It asks for a name and an age. It converts the age to an integer, greets the user, and calculates the age they will reach in ten years.
name = input("What is your name? ")
age = int(input("How old are you? "))
print("Hello,", name)
print("In 10 years you will be", age + 10)

Reading Several Values from One Line

Sometimes the user types several values on one line, separated by spaces. The string method split() cuts a string at every space and returns a list of the pieces. You can store the pieces in separate variables in one step, or convert all of them at once with map().

Try It: Two Numbers on One Line

The Program Input box contains 12 30 on a single line. Click Run Code, then try other pairs of numbers.

What this code does: It reads one line, splits it into two pieces, converts both pieces to integers, adds them, and prints the sum inside a sentence built with an f-string.
line = input("Enter two numbers: ")
first, second = line.split()
total = int(first) + int(second)
print(f"{first} + {second} = {total}")

Try It: Any Number of Values

This version accepts as many numbers as the user types. The Program Input box contains 4 8 15 16 23 42. Click Run Code, then add or remove numbers.

What this code does: It reads one line, splits it, and converts every piece to an integer with map(). It then prints the list, the sum, and the average rounded to two decimal places.
numbers = list(map(int, input("Enter numbers: ").split()))
print("Numbers:", numbers)
print("Sum:", sum(numbers))
print("Average:", round(sum(numbers) / len(numbers), 2))

Putting It Together: A Formatted Receipt

Real programs combine input, calculation, and neatly formatted output. The following example reads an item, a price, and a quantity, and then prints a small receipt with aligned columns. The width in each f-string specification keeps the columns straight.

Try It: A Simple Receipt

The Program Input box is filled with three lines: Pen, 1.5, and 12. Click Run Code, then try another item.

What this code does: It reads an item name, a price, and a quantity. It prints a line of dashes, a header row, a row with the item and its total cost, and a closing line of dashes. Each column has a fixed width, so the numbers line up.
item = input("Item: ")
price = float(input("Price: "))
qty = int(input("Quantity: "))

print("-" * 24)
print(f"{'Item':<10}{'Qty':>4}{'Total':>10}")
print(f"{item:<10}{qty:>4}{price * qty:>10.2f}")
print("-" * 24)
Tip: Always tell the user what to type. A prompt such as input("Enter your age: ") is much friendlier than a blank cursor.

Common Mistakes with Input and Output

  • Forgetting to convert input: input() returns text, so input("Age: ") + 1 raises a TypeError. Wrap it in int().
  • Missing parentheses: print "Hello" is old Python 2 style and causes a SyntaxError. In Python 3, print is a function.
  • Forgetting the f: "Hello, {name}" without the f prints the braces literally.
  • Unmatched quotes: a string that starts with " must also end with ". Escape a quote that appears inside, or use the other kind of quotes.
  • Joining text and numbers with +: "Total: " + 5 fails. Use a comma in print(), str(), or an f-string.
  • Too few lines of Program Input: every input() call needs its own line in the Program Input box, otherwise an EOFError appears.
  • A raw string ending with a backslash: r"C:\folder\" is a syntax error, because the final backslash escapes the closing quote.

Key Takeaways

  • print() shows values and accepts sep and end to control separators and endings.
  • Escape sequences such as \n and \t add special characters, and a raw string with an r prefix switches them off.
  • f-strings insert values with { } and format them with specifications such as :.2f, :,, :%, and :>8.
  • str.format() and the % operator are older formatting styles that you will see in existing code.
  • input() returns a string, so convert it with int() or float() before calculating.
  • split() and map() read several values from a single line.
  • On this site, supply one line of Program Input for every input() call.

Frequently Asked Questions

How do I print output in Python?

Use the built-in print() function, for example print(“Hello”). You can pass several values separated by commas, and print() converts each one to text, separates them with a space, and ends the line automatically.

How do I print without a new line in Python?

Pass the end parameter, for example print(“Loading”, end=””). By default print() ends with a new line. Setting end to an empty string, or to another text such as “…”, makes the next output continue on the same line.

What does the sep parameter do in print()?

The sep parameter sets the text that print() places between multiple values. The default is a single space. For example, print(“2026”, “11”, “22”, sep=”-“) displays 2026-11-22.

How do I take user input in Python?

Use the input() function, for example name = input(“Your name: “). It displays the prompt, waits for the user to type a line, and returns the text. Convert the result with int() or float() if you need a number.

Why does input() always return a string?

The input() function reads raw text from the user and cannot know what type you intended, so it always returns a str, even when the user types digits. Use int() for whole numbers or float() for decimal numbers to convert the text.

How do I read multiple values on one line in Python?

Read the line with input(), then use the split() method to cut it into pieces. For example, a, b = input().split() stores two values, and numbers = list(map(int, input().split())) converts every value to an integer.

How do I format a number to two decimal places in Python?

Use an f-string with the .2f format specification, for example f”{price:.2f}”. It displays the number with exactly two digits after the decimal point. You can also use round(price, 2), but the f-string keeps trailing zeros.

What is the difference between f-strings, format() and % formatting?

All three insert values into text. The % operator is the oldest style, str.format() uses {} placeholders and is more flexible, and f-strings, introduced in Python 3.6, put the expressions directly inside the string. F-strings are the shortest and most readable, so they are recommended for new code.

Ready for the next step?Learn how to calculate and compare values with operators.
Next: Operators & Expressions →