By WebNest Studio Engineering Team
Python Tutorial
Input and Output in Python
Most programs need to talk to the user: read values they type and show results in a readable way. Python's input() reads a line from the keyboard and print() writes to the screen, while f-strings and format specifiers make output look professional.
This lesson covers reading input and converting it to numbers, validating input, reading several values from one line, and formatting output with widths, alignment and decimal places.
Why it matters
Nearly every program takes some input and shows some result. Two things catch every beginner: input() always gives back text, even when the user types a number, and output usually needs formatting to be readable. Both are solved with a few standard idioms.
Reading Input
input(prompt) shows the prompt, waits for the user to press Enter, and returns what they typed as a string — always a string, even if they typed digits. Convert it with int() or float(). Conversion of invalid text raises ValueError, so real programs validate input in a loop with try/except.
Multiple Values
To read several values from one line, split the string: a, b = input().split(), and convert with map(int, input().split()). This pattern is common in coding challenges.
Formatting Output
f-strings (f"{value}") insert values into text. After a colon you can add a format specifier: {price:.2f} (two decimals), {n:,} (thousands separator), {name:<10} / {name:>10} / {name:^10} (left/right/centre align in 10 characters), {ratio:.1%} (percentage), and {value=} (prints the expression and its value, great for debugging).
Examples
Reading input and converting it
name = input("Your name: ")
age = int(input("Your age: "))
print(f"Hello {name}, next year you will be {age + 1}.")
Your name: Your age: Hello Asha, next year you will be 25.
Reading several numbers from one line
a, b, c = map(int, input("Enter three marks: ").split())
print("Total:", a + b + c)
print("Average:", (a + b + c) / 3)
Enter three marks: Total: 255
Average: 85.0
Validating input with a loop
while True:
text = input("Quantity (1-10): ")
try:
quantity = int(text)
except ValueError:
print(f"'{text}' is not a whole number.")
continue
if 1 <= quantity <= 10:
break
print("Please enter a number between 1 and 10.")
print("You ordered", quantity)
Quantity (1-10): 'five' is not a whole number.
Quantity (1-10): Please enter a number between 1 and 10.
Quantity (1-10): You ordered 3
Formatting a neat report
items = [("Python course", 1, 2999), ("Workbook", 3, 499.5), ("Stickers", 10, 25)]
print(f"{'Item':<15}{'Qty':>5}{'Amount':>12}")
print("-" * 32)
total = 0
for name, qty, price in items:
amount = qty * price
total += amount
print(f"{name:<15}{qty:>5}{amount:>12,.2f}")
print("-" * 32)
print(f"{'Total':<20}{total:>12,.2f}")
print(f"{0.1845:.1%} of students scored above 90")
print(f"{total=}")
Item Qty Amount
--------------------------------
Python course 1 2,999.00
Workbook 3 1,498.50
Stickers 10 250.00
--------------------------------
Total 4,747.50
18.4% of students scored above 90
total=4747.5
Common Mistakes
- Doing arithmetic on input() without converting: "5" + "3" gives "53".
- Crashing on invalid input instead of validating with try/except.
- Using float for money and printing raw values like 0.30000000000000004 instead of formatting.
- Building output with + and str() everywhere instead of f-strings.
Exercise
The variable line holds text in the form that input() would return if the user typed three numbers. Convert them to integers and print their sum, and their average to two decimal places.
Expected output: Sum: 12 then Average: 4.00
line = "3 4 5" # what input() would return
# TODO: split the line and convert each part to an int
# TODO: print the sum
# TODO: print the average with two decimal places
Show hints
line.split()gives a list of strings, andmap(int, ...)converts each one.- In an f-string,
{value:.2f}shows two decimal places.
Show solution
line = "3 4 5" # what input() would return
numbers = list(map(int, line.split()))
total = sum(numbers)
print(f"Sum: {total}")
print(f"Average: {total / len(numbers):.2f}")
Quick quiz
1. The user types 25 in response to age = input(). What is the type of age?
- A. int
- B. str
- C. float
- D. It depends on what was typed
Show answer
B. input() always returns a string. Convert it with int() or float().
2. What does int("3.5") do?
- A. Returns 3
- B. Returns 4
- C. Returns 3.5
- D. Raises ValueError
Show answer
D. int() accepts only text that is a whole number. Use float("3.5") first.
3. What does f"{3.14159:.2f}" produce?
- A. 3.14
- B. 3.14159
- C. 3.1
- D. 03.14
Show answer
A. .2f formats the number with two digits after the decimal point.
Interview questions
How do you read several numbers typed on one line?
Show answer
Read the line, split it on whitespace and convert each piece: numbers = list(map(int, input().split())). When the count is known, the values can be unpacked directly: a, b = map(int, input().split()).
How do you make sure the user enters a valid number?
Show answer
Ask inside a loop and attempt the conversion in a try block. If int() raises ValueError, show a message and ask again; when the conversion succeeds, leave the loop with break. Input from a user should never be assumed to be valid.
Key Points to Remember
- input() always returns a string; convert with int() or float().
- Validate input in a loop with try/except ValueError.
- map(int, input().split()) reads several numbers from one line.
- f-string format specifiers control decimals, alignment, separators and percentages.
- f"{expr=}" prints an expression and its value for quick debugging.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering