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
\nand\tthat 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 withint()orfloat().
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.
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")print() puts a space between them. The output is Hello World.sep="-" replaces the space between the values with a hyphen. The output is 2026-11-22.end="..." replaces the usual new line with three dots, so the next output continues on the same line.Loading...done. The new line at the end is the default end.print() with no values prints only a new line, which creates an empty line in the output.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:
\nstarts a new line.\tinserts 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.
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")\t inserts a tab character, so Asha is shown after a gap.\n breaks the text, so the output has two lines: Line one and Line two.\" prints a double quotation mark without ending the string. The output is She said "Hi".\' prints an apostrophe inside a string that is written with single quotes. The output is It's fine.\\ prints a single backslash, so the output is C:\Users\Asha.r prefix switches escape processing off. The output is C:\new\table, and the \n and \t are not turned into a new line and a tab.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.
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}")name refers to the string "Asha".price refers to the float 1234.5.rate refers to 0.075, which is 7.5 percent.{name} with its value. The output is Hello, Asha!.:.2f formats the number as a fixed-point value with 2 digits after the point. The output is Price: 1234.50.Price: 1,234.50.:.1% multiplies the value by 100, shows 1 decimal, and adds a percent sign. The output is Rate: 7.5%.> aligns to the right, < to the left, and ^ to the center. The output is [ Asha] [Asha ] [ Asha ].:03d prints an integer at least 3 characters wide and fills the gap with zeros. The output is 007.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.
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)item refers to the string "pen".qty refers to the integer 3.{} gets qty and the second gets item. The output is 3 x pen.{1} takes the argument at position 1, which is qty, and {0} takes the argument at position 0, which is item. The output is 3 x pen again.pen costs 1.5.%s inserts a string and %d inserts an integer. The values are supplied as a tuple after the %. The output is pen x 3.%.1f prints a float with 1 digit after the decimal point. The output is 3.1.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 eachinput()call. If you provide fewer lines than the program asks for, Python stops with anEOFError. 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.
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)input() shows the prompt, reads the first line of the Program Input box, and returns it as text. The text Asha is stored in name.int() converts it to the number 20. If the text is not a whole number, Python stops with a ValueError.Hello, Asha.age is an integer, age + 10 is 30. The output is In 10 years you will be 30.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.
line = input("Enter two numbers: ")
first, second = line.split()
total = int(first) + int(second)
print(f"{first} + {second} = {total}")"12 30", is stored in line as a single string.line.split() cuts the text at the space and returns the list ["12", "30"]. The two items are unpacked into first and second. The line must contain exactly two pieces, otherwise Python raises a ValueError.int() before the addition. The result is 42.12 + 30 = 42.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.
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))input() reads the line, .split() makes a list of strings, map(int, ...) converts each string to an integer, and list() collects the results into the list [4, 8, 15, 16, 23, 42].Numbers: [4, 8, 15, 16, 23, 42].sum() adds all the numbers. The output is Sum: 108.len() counts, and round(..., 2) keeps two decimal places. The output is Average: 18.0.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.
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)input() reads the first line of the Program Input box, Pen, as text.1.5.12."-" * 24 repeats the hyphen 24 times, which makes a line of dashes.Item is left-aligned in 10 characters, and Qty and Total are right-aligned in 4 and 10 characters. The single quotes inside the double-quoted f-string keep the quotation marks from clashing.price * qty is calculated inside the braces and shown with 2 decimals in a field of 10. The total is 18.00.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, soinput("Age: ") + 1raises aTypeError. Wrap it inint(). - Missing parentheses:
print "Hello"is old Python 2 style and causes aSyntaxError. In Python 3,printis a function. - Forgetting the f:
"Hello, {name}"without thefprints 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: " + 5fails. Use a comma inprint(),str(), or an f-string. - Too few lines of Program Input: every
input()call needs its own line in the Program Input box, otherwise anEOFErrorappears. - 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 acceptssepandendto control separators and endings.- Escape sequences such as
\nand\tadd special characters, and a raw string with anrprefix 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 withint()orfloat()before calculating.split()andmap()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.