Learning to talk to your program is the first big step in Python. This beginner-friendly guide explains Python input and output for beginners with simple examples you can run today. You’ll learn how to read user input with input(), print results to the screen, format output with f-strings, and save/load data from files. By the end, you’ll be comfortable building simple Python programs using input and print.
What are input and output in Python?
Input means data that comes into your program, usually typed by a user or read from a file. Output means information your program shows to the user or writes to a file. For console programs:
- Input: use the built-in
input()function to read a line of text from the keyboard. - Output: use the built-in
print()function to show text on the screen.
These are the basic tools for interactive scripts, quick calculators, simple games, and many classroom assignments. This Python input and output tutorial keeps examples short and clear for students and new Python learners.
Quick comparison: Python input and output for beginners
| Feature | Keyboard Input ( input()) |
Screen Output ( print()) |
File I/O ( open(), read/write) |
|---|---|---|---|
| Purpose | Ask user for data at runtime | Show results or messages | Save data for later or load existing data |
| Core API | text = input(prompt) |
print(*objects, sep, end) |
with open(path, mode, encoding) |
| Data type | Returns str (convert to int/float if needed) |
Accepts any Python object (prints its text form) | Text mode uses str with an encoding (e.g., UTF‑8) |
| Typical extras | .split(), strip(), validation with try/except |
Formatting with f-strings, custom sep/end |
Use encoding="utf-8", newline="" for CSV |
| Tiny example | age = int(input("Age: ")) |
print(f"Age: {age}") |
Path("data.txt").write_text("hello", encoding="utf-8") |
Reading user input with input()
The function input() reads one line from the user, removes the trailing newline, and returns a string. You can optionally pass a prompt to show a message first.
Syntax
Basic example
print("Hello,", name)
What's your name? Aisha
Hello, AishaReading numbers from user input
Because input() always returns a string, convert it to the type you need:
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
print(f"You are {age} years old and {height} m tall.")Getting multiple inputs in one line
You can ask the user to enter several values separated by spaces or commas and then split the string.
# Space-separated integers
a, b = map(int, input("Enter two integers: ").split())
print(f"Sum = {a + b}, Product = {a * b}")
# Comma-separated values with stripping
raw = input("Enter city, country: ") # e.g., "Lahore, Pakistan"
city, country = [part.strip() for part in raw.split(",")]
print(f"City: {city} | Country: {country}")Beginner guide to input validation (handling invalid input)
Users make mistakes. Your program should handle them. Use try/except in a loop to keep asking until input is valid.
def read_int(prompt="Enter an integer: "):
while True:
text = input(prompt)
try:
return int(text)
except ValueError:
print("Please enter a valid whole number.")
count = read_int()
print(f"You entered: {count}")Common mistakes when using input()
- Forgetting to convert types: Wrong
age = input(...)then doing math; Rightage = int(input(...)). - Expecting
input()to evaluate expressions or return numbers automatically. In Python 3, it always returns astr. - Not handling empty input. Consider checking
if not text.strip():.
Printing output with print()
The print() function writes text to the screen (standard output). It can print any number of objects, separated by a space by default, followed by a newline.
Syntax
python print function examples
print("Hello, world!")
# Print variables and text together
name = "Aisha"
score = 96
print("Student:", name, "Score:", score)
# Control separators and line endings
print("A", "B", "C", sep="-") # A-B-C
print("Loading", end="") # No newline
print("...done") # continues same line
# Immediate output (useful for progress bars)
for i in range(3):
print(".", end="", flush=True)
print(" complete")
Hello, world!
Student: Aisha Score: 96
A-B-C
Loading...done
... completePrinting to a file or to error output
You can redirect print() to a file or to standard error.
# Print a message to the error stream
print("Warning: low disk space", file=sys.stderr)
# Write text to a file
with open("log.txt", "w", encoding="utf-8") as f:
print("Session started", file=f)
How to format output in Python with f-strings
For neat, readable output, use f-strings (formatted string literals). They are short, fast, and clear for beginners.
# Basic variable interpolation
name = "Aisha"
print(f"Hello, {name}!")
# Numbers with 2 decimal places
price = 12.5
print(f"Price: ${price:.2f}")
# Thousands separator and alignment
n = 1234567
print(f"Count: {n:,}") # 1,234,567
print(f"|{n:>12,}|") # right-aligned in 12 spaces
# Percentages
ratio = 0.8732
print(f"Accuracy: {ratio:.1%}")
# Dates using format codes
from datetime import date
today = date.today()
print(f"Today is {today:%Y-%m-%d}")Format specifications follow Python’s “Format Specification Mini-Language,” which gives control over width, precision, alignment, and more.
Flow of a beginner Python I/O program
input()returns str
int(), float(), try/exceptcalculate/decide
f-strings
print()
open()read()/write(), UTF‑8CSV / JSON
Simple Python programs using input and print
1) Add two numbers
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"{a} + {b} = {a + b:.2f}")2) Grade average with validation
def read_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Please enter a valid number.")
scores = [read_float("Enter score 1: "),
read_float("Enter score 2: "),
read_float("Enter score 3: ")]
avg = sum(scores) / len(scores)
print(f"Average = {avg:.2f}")3) Getting multiple inputs in one line
a, b, c = map(int, input("Enter three integers: ").split())
print(f"Min={min(a,b,c)}, Max={max(a,b,c)}, Sum={a+b+c}")Basic file input and output for students
Console I/O is great for quick practice, but many tasks need files. In Python 3.14, always specify the encoding for portable text handling. UTF‑8 is a safe, common choice on all platforms.
Write and read text files with open()
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("Hello from CodDesire!n")
f.write("Python makes file I/O easy.n")
# Read the file back
with open("notes.txt", "r", encoding="utf-8") as f:
content = f.read()
print("File content:")
print(content)
Using pathlib for simpler file code
path = Path("message.txt")
path.write_text("Pathlib writes text with ease.", encoding="utf-8")
text = path.read_text(encoding="utf-8")
print(text)
Structured data: JSON and CSV basics
For simple data exchange, JSON and CSV are common and supported by the standard library.
import json
student = {"name": "Aisha", "roll": 21, "scores": [88, 92, 79]}
with open("student.json", "w", encoding="utf-8") as f:
json.dump(student, f, indent=2, ensure_ascii=False)
with open("student.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(f"Loaded: {loaded['name']} with {len(loaded['scores'])} scores.")
import csv
rows = [("name", "math", "science"),
("Aisha", 88, 92),
("Ali", 75, 81)]
with open("scores.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(rows)
with open("scores.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Standard streams and bytes vs text
sys.stdin,sys.stdout, andsys.stderrare text streams (they read/write Pythonstr). This is whatinput()andprint()use.- If you need raw bytes, use
sys.stdin.bufferorsys.stdout.bufferand read/writebytes.
# Text output (common)
print("Hello text")
# Bytes output (advanced use)
sys.stdout.buffer.write(b"Hello bytesn")
Practical tips and common mistakes
- Start simple: build small simple Python programs using input and print before moving to files.
- Convert types immediately after
input()if you will do math:n = int(input(...)). - Use f-strings for readable output:
f"{value:.2f}"for two decimals. - When writing files, specify
encoding="utf-8"in Python 3.14 for portability. UTF‑8 becomes the default in Python 3.15, but being explicit is still good practice. - For CSV files, open with
newline=""to avoid extra blank lines on some platforms. - Don’t use
eval()on user input. Validate and convert safely withint(),float(), or custom checks. - Keep prompts clear and helpful. If input is invalid, tell the user what’s expected, then ask again.
- ☐ Write a clear prompt:
input("Enter total items: ") - ☐ Strip/validate text; convert types early:
qty = int(text) - ☐ Use a loop +
try/exceptfor invalid entries - ☐ Format output with f-strings:
f"{value:.2f}" - ☐ For files, open with an explicit encoding:
encoding="utf-8" - ☐ For CSV, use
newline=""when opening files - ☐ Avoid
eval(); never execute user input - ☐ If showing progress, use
flush=Trueor adjustend
Practice: try these quick exercises
- Ask for a name and favorite number, then print a friendly sentence using an f-string.
- Read three floats on one line and print their average to 2 decimal places.
- Write a program that keeps asking for an integer until the user enters one between 1 and 10.
- Create a “mini ledger”: repeatedly read descriptions and amounts, then save them to a CSV file.
FAQ: Python input and output for beginners
What does the input() function do in Python?
input() reads one line from the keyboard, removes the trailing newline, and returns it as a string. It never evaluates or converts the input automatically—convert it yourself with int(), float(), etc.
How do I print variables and text together in Python?
You can pass multiple arguments to print() or use an f-string:
print("Student:", name, "Score:", score)
print(f"Student: {name} | Score: {score}")
How can I read numbers from user input in Python?
Read text with input() and convert it:
age = int(input("Age: "))
height = float(input("Height (m): "))What are f-strings and how do I format output in Python?
F-strings let you embed expressions inside string literals, like f"Value: {x}". They support format specs such as :.2f for decimals or :, for thousands separators.
How do I handle invalid input from users in Python?
Use a loop with try/except to catch ValueError and ask again.
while True:
try:
n = int(input("Enter a whole number: "))
break
except ValueError:
print("That wasn039;t a whole number. Try again.")Where to go next
Continue exploring our Python basics, exercises, and examples on the main CodDesire Python page: CodDesire Python Tutorials. If you’ve mastered reading user input in Python and printing results, you’re ready for conditions, loops, and functions.
Sources and further reading
- Python Tutorial — Input and Output: https://docs.python.org/3/tutorial/inputoutput.html
- Built-in functions:
input(),print(),open()— Python 3.14: https://docs.python.org/3.14/library/functions.html - sys (standard streams): https://docs.python.org/3.14/library/sys.html
- pathlib — Paths and simple file I/O: https://docs.python.org/3.14/library/pathlib.html
- Format Specification Mini-Language: https://docs.python.org/3.14/library/string.html
- PEP 498 — Literal String Interpolation (f-strings): https://peps.python.org/pep-0498/
- PEP 686 — Make UTF‑8 mode default: https://peps.python.org/pep-0686/
With these basics of Python input and output for beginners, you can build interactive scripts, mini calculators, and simple data tools. Keep practicing, and refer back to these examples whenever you need a refresher on how to use input() in Python or how to format clean, readable output.


