Input & Output

Programs talk to the outside world. The simplest channels are the console: print() to show output and input() to read what the user types. This lesson covers both in depth, plus command-line arguments for scripts.

print() in detail

PY print_basics.py
print("Hello")
print("a", "b", "c")
print("a", "b", "c", sep="-")
print("no newline", end=" ")
print("same line")
print()
print("after a blank line")
Output
Hello
a b c
a-b-c
no newline same line

after a blank line

print accepts any number of values, converts each with str(), joins them with sep (a space by default) and finishes with end (a newline by default).

Printing collections and objects

PY print_objects.py
from pprint import pprint

data = {"name": "Ana", "skills": ["python", "sql", "git"], "address": {"city": "Lisbon", "zip": "1100"}}
print(data)
pprint(data, width=40)
Output
{'name': 'Ana', 'skills': ['python', 'sql', 'git'], 'address': {'city': 'Lisbon', 'zip': '1100'}}
{'address': {'city': 'Lisbon',
             'zip': '1100'},
 'name': 'Ana',
 'skills': ['python', 'sql', 'git']}

pprint ("pretty print") wraps nested data across lines, which is much easier to read for large structures. It sorts dictionary keys by default.

Printing to stderr and files

PY print_file.py
import sys

print("Something went wrong", file=sys.stderr)

with open("log.txt", "a") as log:
    print("Saved report", file=log)

Error messages conventionally go to standard error (sys.stderr), so they can be separated from normal output. The file argument also writes to any open file (lesson 43).

input()

input(prompt) shows a prompt, waits for the user to type a line and press Enter, and returns what they typed as a string:

PY input.py
name = input("What's your name? ")
age = int(input("How old are you? "))

print(f"Hi {name}! Next year you'll be {age + 1}.")
Terminal session
What's your name? Ada
How old are you? 36
Hi Ada! Next year you'll be 37.

Remember to convert numeric input with int() or float() — input always returns text. The in-browser editors on this site can't pause for typing, so run input() examples on your own computer.

Validating input

Users type unexpected things. A loop that asks again until the input is valid is a common pattern:

PY validate.py
def ask_int(prompt, low, high):
    while True:
        text = input(prompt).strip()
        try:
            value = int(text)
        except ValueError:
            print("Please enter a whole number.")
            continue
        if low <= value <= high:
            return value
        print(f"Please enter a number from {low} to {high}.")

rating = ask_int("Rate us 1-5: ", 1, 5)
print("Thanks for rating us", rating)

Command-line arguments

Scripts can also take input from the command line. The raw arguments are in sys.argv:

PY greet.py
import sys

# python3 greet.py Ada --shout
args = sys.argv[1:]
name = args[0] if args else "world"
message = f"Hello, {name}!"
print(message.upper() if "--shout" in args else message)

For real tools, the standard library's argparse module parses options, validates them and generates --help text automatically:

PY convert.py
import argparse

parser = argparse.ArgumentParser(description="Convert temperatures.")
parser.add_argument("value", type=float, help="the temperature to convert")
parser.add_argument("--to", choices=["c", "f"], default="c", help="target unit")
args = parser.parse_args()

result = (args.value - 32) * 5 / 9 if args.to == "c" else args.value * 9 / 5 + 32
print(f"{result:.1f}°{args.to.upper()}")
Terminal session
$ python3 convert.py 212 --to c
100.0°C
$ python3 convert.py --help
usage: convert.py [-h] [--to {c,f}] value
...

Reading all of standard input

Scripts that process piped data (cat data.txt | python3 count.py) can read sys.stdin like a file:

PY count.py
import sys

lines = sys.stdin.read().splitlines()
print(f"{len(lines)} lines, {sum(len(l.split()) for l in lines)} words")

Try it yourself

Since the browser editor can't wait for typing, this version simulates the answers in a list — swap answers.pop(0) for input(question) on your own computer:

Try it yourself
Console output