Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 149 ยท Getting Started

Input and Output

Control Python output with print() options like sep and end, read user input with input(), convert it to numbers safely, and format results neatly.

Almost every program talks to someone. It shows results with output and asks for information with input. In Python, the everyday tools for this are two built-in functions you've already met: print() and input().

There's more to both than first appears. In this lesson you'll learn how to control spacing and line endings in print(), send messages to the error stream, read several answers with input(), turn text into numbers, and lay results out neatly with f-strings.

print() takes any number of values, turns each one into text, and writes them on one line separated by spaces:

Python Printing several values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can pass any kind of value: strings, numbers, booleans, lists. print() converts each one with str() before writing it. That's why you don't need to convert price yourself when you pass it as a separate argument.

Compare that with joining strings using +, which only works when both sides are strings:

Python
print("Price: " + price)        # TypeError: can only concatenate str (not "float") to str
print("Price: " + str(price))   # works, but commas or f-strings are simpler

Changing the separator with sep

The space between values comes from the sep (separator) parameter, which defaults to " ". Set it to anything you like, including an empty string:

Python The sep parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

"\n" is the newline character. Putting it in a string starts a new line at that point. You'll learn more of these escape sequences in Strings.

Changing the line ending with end

After the last value, print() writes whatever is in end, which defaults to "\n". That's why each print() normally starts on a new line. Change end to keep printing on the same line:

Python The end parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The final print(" done!") uses the default ending again, so whatever comes next starts on a fresh line.

sep and end are keyword arguments: you write them by name, after the values. You can use both at once, as in print(a, b, sep=":", end="!\n").

Errors go to stderr

Programs have two output streams. Standard output (stdout) is for normal results; standard error (stderr) is for warnings and error messages. Keeping them separate lets someone save a program's results to a file while still seeing problems on screen. Use the file parameter to choose the stream:

Python Writing to stderr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a terminal, both streams normally appear in the same window. Many editors and this site's console show stderr text in a different color.

Note: print() also has a flush parameter. Output is sometimes buffered, meaning collected and written in chunks. print(..., flush=True) forces it out immediately, which matters for progress messages in long-running scripts.

Reading input with input()

input() pauses the program, waits for the user to type a line and press Enter, and returns what they typed as a string. If you pass a prompt, it's shown first:

Python Asking for a name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On this site, answers come from the Input box under the editor, one line per input() call. Edit it and run again to try different answers.

Two details are worth remembering:

  • Add a trailing space to the prompt ("What's your name? "), or the user's typing will be squashed against the question mark.
  • The newline from pressing Enter is not included in the returned string.

input() always returns a string

Even when the user types digits, input() gives you text. Arithmetic on text either fails or does something surprising:

Python Text is not a number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

+ on two strings joins them, so "7" + "5" is "75". Converting with int() turns the text into a whole number first. Use float() instead when decimals are allowed. You'll see all the conversion functions in Type Conversion.

The usual pattern is to convert right away, wrapping the input() call:

Python
age = int(input("Your age: "))
height = float(input("Your height in meters: "))

When the input isn't a number

If the text can't be converted, int() raises a ValueError. Try changing the Input box below to twelve:

Python Invalid numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

int() tolerates spaces around the number, but not letters or a decimal point (int("2.5") fails; use float() for that). Real programs catch the error and ask again. You'll learn how in Exceptions and try/except.

Reading several values from one line

Sometimes it's natural to type several values on one line, like 3 4 5. Read the line once, then split it into pieces with the string method .split():

Python Several numbers on one line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

.split() with no arguments breaks the text wherever there is whitespace and drops the spaces themselves. Later you'll learn shorter ways to convert every piece at once, such as list comprehensions. String Methods covers .split() in detail.

Cleaning up input

People type stray spaces and random capitalization. Two string methods help: .strip() removes whitespace from both ends, and .lower() makes everything lowercase, so comparisons don't depend on how the user typed:

Python Normalizing answers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Methods can be chained: .strip() returns a new string, and .lower() is called on that.

Reading standard input directly

input() is fine for prompts, but programs that process piped text or many lines (as online judges and shell pipelines do) read from the standard input stream sys.stdin. It is an iterable of lines, so a for loop handles any amount of data. Each line keeps its trailing newline, so call .strip() or .rstrip("\n"). The fileinput module goes one step further: it reads the files named on the command line, or standard input when there are none, as one continuous stream of lines.

Python Reading every line of stdin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Formatted output with f-strings

Printing with commas is quick, but you can't control spacing or decimals. An f-string, a string with an f before the opening quote, lets you drop values straight into text inside {} and format them as you go:

Python A tidy receipt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Inside the braces, the part after the colon is a format specification:

  • :.2f shows a number with exactly 2 decimals.
  • :<10 left-aligns in a column 10 characters wide; :>5 right-aligns in 5.

These few patterns already cover most everyday output. String Formatting goes much deeper, with thousands separators, percentages, padding and dates.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does print("a", "b", "c", sep="-") output?

    sep goes between values only, not before the first or after the last.
  2. 2. The user types 4 for both prompts. What does print(input() + input()) show?

    input() returns strings, and + joins strings. Convert with int() first to add them as numbers.
  3. 3. Which call keeps the next print() on the same line?

    end replaces the newline that print() normally writes after the last value.
  4. 4. What happens with int(input()) when the user types 2.5?

    int() only accepts text that looks like a whole number. Use float() for decimals, then int() or round() if you need a whole number.
  5. 5. Where should a program print warnings and error messages?

    Sending problems to stderr keeps them separate from the program's normal results on stdout.

Summary

  • print() writes values separated by sep (default a space) and followed by end (default a newline).
  • file=sys.stderr sends messages to the error stream; flush=True writes immediately.
  • input(prompt) returns what the user typed as a string, without the newline.
  • Convert input with int() or float(); invalid text raises ValueError.
  • .split() breaks one line into pieces; .strip() and .lower() clean up answers.
  • f-strings like f"{total:.2f}" and f"{name:<10}" give you control over layout and decimals.

Next: Data Types, a tour of the kinds of values Python works with.