Python Input/Output
Beginner Python Basics

Python Input and Output

1Python Input/Output: overview

Input and output is how a program talks to its user: input() reads a line the user types and returns it as a string, and print() writes text back to the screen.

GoalBy the end you can ask the user for values with input(), convert them to numbers, and print neatly formatted results using sep, end and f-strings.

Before this lesson: Python Variables, Python Data Types, Python Strings

2Python Input/Output: diagram

Python Input and Outputkeyboarduser types 3textinput()returns "3"strint()"3" -> 3intcalculate3 * 12.5floatprint()shows 37.5
Typed text travels from the keyboard (stdin) into input(), which always hands back a string. Convert it with int() or float() before calculating, then print() sends the result to the screen.

3Python Input/Output: explained step by step

So far, every value in your programs has been typed straight into the code. Real programs usually get at least some of their data from the person using them. Python's two basic tools for that conversation are input() for reading and print() for writing.

Reading text with input()

input("prompt") shows the prompt, waits for the user to type a line and press Enter, and then returns what they typed as a string. You normally store the result in a variable:

name = input("What is your name? ")
print("Nice to meet you,", name)

End the prompt with a space so the answer doesn't stick to the question.

Running it on this site: a program in your browser can't pause to wait for the keyboard, so type your answers into the Input (stdin) box before pressing Run — one line for each input() call. When the program runs, each line is handed to the next input() and shown after its prompt, just as it would appear in a terminal. If there are fewer lines than input() calls, you get an EOFError.

input() always gives you a string

Even when the user types digits, input() returns text: typing 7 gives you "7", not 7. Convert the result before doing maths with it:

age = int(input("Age: "))                 # whole numbers
height = float(input("Height in m: "))    # decimals

If the text can't be converted — say the user types seven — int() raises a ValueError. The lesson on exceptions shows how to handle that gracefully.

More control over print()

print() accepts any number of values, puts a space between them and finishes with a new line. Two optional arguments change that:

  • sep — what goes between the values (a space by default)
  • end — what goes after the last value (a new line, "\n", by default)
Python
print("2026", "10", "20", sep="-")
print("Loading", end="...")
print("done")
print("a", "b", "c", sep="")
print()
print("The empty print() above added a blank line")

Formatting output with f-strings

For anything more than a couple of values, f-strings give you the most control. Inside {} you can add a format code after a colon:

  • {x:.2f} — exactly two decimal places
  • {x:>8} or {x:<8} — right- or left-align in a space 8 characters wide
  • {x:,} — add thousands separators
Python
item = "Tea"
price = 3.456
cups = 12
print(f"{item:<10}{price:>8.2f}")
print(f"{'Total':<10}{price * cups:>8.2f}")
print(f"Cups sold this year: {cups * 1000:,}")

Aligning values to a fixed width makes them line up in neat columns, which is perfect for receipts, scoreboards and simple tables.

Quick reference: Python Input/Output

4Python Input/Output: syntax

text = input("Prompt: ")            # always returns a str
whole = int(input("Count: "))       # convert to int
decimal = float(input("Price: "))   # convert to float
print(a, b, sep=", ", end="\n")     # sep between values, end after them
print(f"{price:.2f}")               # exactly two decimal places
print(f"{name:<10}{qty:>5}")        # left / right align in a fixed width

5Python Input/Output: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
name = input("Your name: ")
tickets = int(input("How many tickets? "))
price = float(input("Price per ticket: "))

total = tickets * price
code = name[:3].upper() + "-" + str(tickets)

print()
print("Booking for", name)
print("Tickets:", tickets, "x", price)
print(f"Total: ${total:.2f}")
print("Booking code:", code)
print("Thank you", name, sep=", ", end="!\n")
Expected outputYour name: Priya
How many tickets? 3
Price per ticket: 12.5

Booking for Priya
Tickets: 3 x 12.5
Total: $37.50
Booking code: PRI-3
Thank you, Priya!

7Python Input/Output: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1input() shows the prompt and waits. The first input line, Priya, comes back as the string "Priya". On this site the typed text appears after the prompt, just like in a terminal.
  2. Line 2The second line, 3, arrives as the text "3". int() turns it into the number 3 so it can be used in a calculation.
  3. Line 3float() converts the text "12.5" into the decimal number 12.5.
  4. Line 53 × 12.5 = 37.5. This only works because both values were converted to numbers first.
  5. Line 6String tools from the previous lesson build a booking code: the first three letters in capitals, a dash, and str(tickets).
  6. Line 8print() with no values prints an empty line, separating the questions from the summary.
  7. Line 9-10By default print() puts a single space between the values it is given.
  8. Line 11The format code :.2f shows exactly two decimals, so 37.5 is printed as 37.50.
  9. Line 12The booking code built on line 6 is printed: PRI-3.
  10. Line 13sep=", " puts a comma and a space between the values, and end="!\n" adds an exclamation mark before the usual line break.

8Python Input/Output: common mistakes

Doing maths on input() without converting

✗ Wrong

boxes = input("How many boxes? ")
print("Items:", boxes * 2)
No error, but typing 3 prints Items: 33 instead of 6

✓ Right

boxes = int(input("How many boxes? "))
print("Items:", boxes * 2)

input() returned the text "3", and text times 2 repeats it. Convert with int() as soon as you read the value.

Using int() for an answer with decimals

✗ Wrong

price = int(input("Price: "))
ValueError: invalid literal for int() with base 10: '4.99' (when the user types 4.99)

✓ Right

price = float(input("Price: "))
print(price * 2)

int() only understands whole numbers. Use float() whenever the user might type a decimal point.

Joining a number to text with +

✗ Wrong

total = 42.5
print("Total: " + total)
TypeError: can only concatenate str (not "float") to str

✓ Right

total = 42.5
print(f"Total: {total}")

+ can only join text to text. Pass the values to print() separated by a comma, or use an f-string, which converts the number for you.

9Python Input/Output: exercises

Write your answer, then press Check. The checks run in your browser.

1. Greet the user

Write code Easy

Ask for the user's name with input("Name: ") and store it in a variable called name. Then print a greeting in exactly this form, using whatever name was typed:

Hello, Sam!

The checker types Sam as the input.

Your code
# read the name, then print the greeting

2. Predict the conversation

Predict the output Medium

When this program runs, the user types 4. Type exactly what appears on the screen — remember that the typed input is shown right after the prompt.

Read this code
n = input("Number: ")
print(n * 3)
print(int(n) * 3)
print("A", "B", sep="-", end="!\n")
print(f"{int(n) / 3:.1f}")

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

Why does input() always return a string in Python?

The keyboard only produces text, and Python can't know whether "42" is meant to be a number, a code or part of a name. Converting is your decision: wrap the call in int() or float() when you need a number.

How do I give input to my program on this website?

Type your answers into the Input (stdin) box before you press Run, one line per input() call. Each line is passed to the next input() and shown after its prompt. If there are fewer lines than input() calls, Python raises an EOFError.

How do I print without moving to a new line?

Pass end to print(): print("Loading", end="") prints the text without a line break, so the next print() continues on the same line. Use end=" " to leave a space instead.

Further reading

10Next lesson

Up nextPython if, elif and elseAn if statement lets a program make a decision: it checks a condition and runs a block of code only when that condition…

Related:
Python Exceptions: try, except, else and finallyPython File HandlingPython Calculator Project

← Python f-Strings · All Python Basics lessons · Practise in the IDE