Python Input and Output: Complete Guide

Published on: July 10, 2026
Reading time: 4 minutes
notebook mostrando tela a teclado

Python input and output are the foundations of interactive programs. Input brings data into an application. Output presents results to users, files, or other systems.

A calculator reads numbers, processes them, and displays an answer. A registration program receives a name and email, validates them, and saves a record. Even large applications rely on the same basic flow: receive, process, return.

What counts as input and output?

Input can come from a keyboard, file, command-line argument, API, database, sensor, or graphical interface. Output can go to the terminal, a file, a web response, a database, or a log.

This guide focuses on terminal and file operations because they are the best starting point. For focused coverage, see the separate guides to Python input() and Python print().

Reading text with input()

The built-in input() function pauses a program, shows an optional prompt, and returns what the user typed.

name = input("What is your name? ")
print(f"Hello, {name}!")

The return value is always a string, even when the user enters digits.

age = input("Age: ")
print(type(age))  # str

The official input() documentation describes this behavior and how end-of-file conditions are reported.

Converting numeric input

Use int() for whole numbers and float() for decimal values:

quantity = int(input("Quantity: "))
price = float(input("Unit price: "))

total = quantity * price
print(f"Total: ${total:.2f}")

Conversion can fail when the user types invalid text. A robust program validates input rather than assuming it is correct.

Validating user input

while True:
    raw_age = input("Enter your age: ").strip()

    try:
        age = int(raw_age)
    except ValueError:
        print("Enter a whole number.")
        continue

    if age < 0:
        print("Age cannot be negative.")
        continue

    break

print(f"Valid age: {age}")

This loop separates conversion errors from business rules. The guide to try and except explains how to catch specific exceptions without hiding unrelated problems.

Cleaning text input

Methods such as strip(), lower(), and casefold() make comparisons more reliable:

answer = input("Continue? [y/n] ").strip().casefold()

if answer in {"y", "yes"}:
    print("Continuing...")
elif answer in {"n", "no"}:
    print("Stopping...")
else:
    print("Unknown option")

The Python strings guide covers slicing, searching, replacement, and formatting methods used to normalize text.

Reading multiple values

split() separates one line into parts:

first_name, last_name = input("First and last name: ").split(maxsplit=1)

For several numbers, combine split() with conversion:

numbers = [float(value) for value in input("Enter numbers: ").split()]
print(sum(numbers))

Validate the number of parts when a fixed format is required.

Basic output with print()

print() can display strings, numbers, variables, and multiple objects:

product = "Headphones"
price = 49.90

print(product)
print("Price:", price)
print("Product:", product, "Price:", price)

By default, items are separated by spaces and each call ends with a newline.

Controlling separators and line endings

print("2026", "07", "10", sep="-")
print("Loading", end="")
print("...done")

The sep parameter controls text between arguments. The end parameter changes what follows the final argument.

Formatting output with f-strings

F-strings are a clear way to combine text and expressions:

name = "Jordan"
score = 87.456

print(f"{name} scored {score:.1f} points")

They also support alignment, percentages, thousands separators, and date formats:

revenue = 1250340.5
rate = 0.1875

print(f"Revenue: ${revenue:,.2f}")
print(f"Growth: {rate:.1%}")

Review formatting numbers and currency with f-strings for more patterns.

Creating readable tables

products = [
    ("Keyboard", 59.90),
    ("Mouse", 24.50),
    ("Monitor", 219.00),
]

print(f"{'Product':<15} {'Price':>10}")
print("-" * 26)

for name, price in products:
    print(f"{name:<15} ${price:>9.2f}")

Alignment specifiers make terminal reports easier to scan without an external library.

Escape characters

Backslash sequences represent special characters:

print("First line\nSecond line")
print("Name\tScore")
print("She said: \"Hello\"")

Use raw strings for Windows-style paths or regular expressions when backslashes should remain literal:

path = r"C:\Users\Alex\Documents"

Writing output to a file

The print() function can write to an open text file:

with open("report.txt", "w", encoding="utf-8") as file:
    print("Monthly Report", file=file)
    print("Revenue: $12,500.00", file=file)

Using with closes the file automatically, even when an error occurs. The tutorial on opening files with with explains this context-manager pattern.

Reading text files

with open("notes.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)

For large files, iterate line by line:

with open("events.log", encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        print(line_number, line.rstrip())

The complete guide to reading TXT files covers read(), readline(), and iteration.

Appending instead of replacing

Mode "w" replaces a file. Mode "a" appends:

with open("activity.log", "a", encoding="utf-8") as file:
    print("User signed in", file=file)

Choose the mode intentionally. Accidentally opening an important file with "w" can destroy its previous contents.

Command-line input

Small automation tools often receive arguments when they start. The standard library exposes them through sys.argv:

import sys

if len(sys.argv) != 2:
    print("Usage: python greet.py NAME")
    raise SystemExit(2)

print(f"Hello, {sys.argv[1]}!")

For professional command-line interfaces, argparse adds help text, types, flags, and validation. See the guide to building a CLI with argparse.

Practical project: expense calculator

def read_positive_float(prompt):
    while True:
        try:
            value = float(input(prompt))
        except ValueError:
            print("Enter a valid number.")
            continue

        if value < 0:
            print("The value cannot be negative.")
            continue

        return value

expenses = []

while True:
    description = input("Expense description (blank to finish): ").strip()
    if not description:
        break

    amount = read_positive_float("Amount: $")
    expenses.append((description, amount))

print("\nExpense Summary")
print("-" * 32)

for description, amount in expenses:
    print(f"{description:<20} ${amount:>9.2f}")

print("-" * 32)
print(f"{'Total':<20} ${sum(amount for _, amount in expenses):>9.2f}")

This project combines reusable functions, validation, lists, loops, formatted output, and a clear stopping rule.

Common mistakes

  • Forgetting that input() returns a string.
  • Catching every exception with a broad except.
  • Failing to strip whitespace before comparisons.
  • Building output with many + operations instead of f-strings.
  • Opening files without an explicit encoding.
  • Using write mode when append mode was intended.
  • Trusting user input without range or format validation.

Best practices

Write small input functions, validate close to the point of entry, separate user interaction from business logic, make error messages specific, and keep file operations inside context managers. This separation also makes code easier to test.

The official Python input and output tutorial covers string formatting and file operations in more detail.

Conclusion

Python input and output connect a program to its users and data. Master input(), explicit conversion, validation loops, print(), f-strings, and safe file handling. These skills are enough to build useful terminal applications before moving to APIs, databases, or graphical interfaces.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Programador pensando enquanto analisa código em dois monitores
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Learn Programming from Scratch: Beginner Guide

    Learn programming from scratch with a practical roadmap covering logic, languages, tools, exercises, projects, debugging, Git, and consistent study habits.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    ícone de loop com o texto 'For' abaixo
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python for Loops: Complete Beginner Guide

    Learn Python for loops with sequences, range, enumerate, zip, dictionaries, nested loops, break, continue, comprehensions, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Manipulação e formatação de strings em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Strings: Complete Beginner Guide

    Learn Python strings with creation, indexing, slicing, methods, formatting, Unicode, searching, validation, splitting, joining, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    código Python de uma tupla com o texto separado formando a frase "O que são tuplas?"
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Tuples: Complete Beginner Guide

    Learn Python tuples with creation, packing, unpacking, indexing, immutability, methods, named records, function returns, and practical examples.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    símbolo de PI
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Floats: Complete Beginner Guide

    Learn Python floats with decimal values, arithmetic, conversion, rounding, precision limits, comparisons, Decimal, math functions, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Dicionário com o logo do Python em uma página e o texto 'Dicionário Python'
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Dictionaries: Complete Beginner Guide

    Learn Python dictionaries from scratch: keys, values, methods, loops, nested data, comprehensions, merging, safe access, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026