| layout | default |
|---|---|
| title | Input and Output |
| parent | Lessons |
| nav_order | 5 |
| permalink | /lessons/input-and-output/ |
| course_lesson | true |
| course_index | 05 |
| previous_page | /lessons/operators/ |
| previous_title | Operators |
| next_page | /lessons/control-flow/ |
| next_title | Control Flow |
Programs become useful when they receive information and communicate results clearly.
Input is the program's ear: it listens to what a person types. Output is the program's voice: it displays a clear answer. A friendly program asks one clear question at a time.
input() displays a prompt, waits for the user, and returns the entered text without the final Enter key:
name = input("What is your name? ").strip()
print(f"Welcome, {name}!").strip() removes accidental spaces at the beginning and end. It does not remove spaces between words.
Important fact:
input()always returns a string (str). This is true even when the person types digits.
Try this program and enter 25:
age_text = input("Enter your age: ")
print(age_text)
print(type(age_text))Output:
25
<class 'str'>
The value looks like a number to us, but Python received keyboard characters. Convert it only when the program needs number operations:
age_text = input("Enter your age: ")
age = int(age_text)
print(age)
print(type(age))keyboard -> input() -> str -> int() or float() when needed
Convert numeric input explicitly:
quantity = int(input("Quantity: "))
price = float(input("Price: "))The inner input() runs first. Its string result is passed to int() or float().
print() displays values and ends with a newline by default:
print("Python")
print("is enjoyable")It accepts multiple values and separates them with a space:
print("Total", 125) # Total 125Change the separator with sep:
print(2026, 8, 5, sep="-") # 2026-8-5Change the ending with end:
print("Loading", end="...")
print("done") # Loading...doneEscape characters represent special formatting inside a string:
| Sequence | Meaning |
|---|---|
\n |
new line |
\t |
tab |
\\ |
backslash |
\" |
double quote |
\' |
single quote |
print("Name:\tRavi\nCity:\tPune")Use triple quotes for a multi-line string when appropriate.
An f-string inserts expressions inside {}:
name = "Ravi"
total = 125.5
print(f"{name} paid Rs. {total:.2f}")Useful format specifiers include .2f for two decimal places and >10 for right alignment:
print(f"{'Item':<12}{'Price':>8}")
print(f"{'Pen':<12}{12.5:>8.2f}")Write the conversation before writing code:
Product name: Notebook
Quantity: 2
Unit price: 45.50
Total: 91.00
Then identify the type of every input and the formula for the result.
item = input("Item: ").strip()
quantity = int(input("Quantity: "))
unit_price = float(input("Unit price: "))
total = quantity * unit_price
print("\n--- Receipt ---")
print(f"Item: {item}")
print(f"Quantity: {quantity}")
print(f"Total: Rs. {total:.2f}")This is clear because each value has a label and the money value has consistent formatting.
- Forgetting that input is text.
- Leaving user spaces uncleaned.
- Printing a calculation expression as text instead of evaluating it.
- Using many commas when one formatted f-string would be clearer.
- Mixing prompts, calculations, and output so the program is difficult to change.
age = input("Age: ")
next_age = age + 1
print(next_age)Clue: convert the input before adding a number.
first = input("First number: ")
second = input("Second number: ")
total = first + second
print(int(total))If the inputs are 2 and 3, this prints 23. Convert each input before addition.
name = input("Name: ")
print("Hello, {name}!")Clue: an f-string begins with f before the opening quote.
Show Bug Hunter fixes
# Bug 1
age = int(input("Age: "))
next_age = age + 1
print(next_age)
# Bug 2
first = int(input("First number: "))
second = int(input("Second number: "))
total = first + second
print(total)
# Bug 3
name = input("Name: ")
print(f"Hello, {name}!")Optional deeper look: where do input and output go?
The terminal provides a text input stream called standard input. input() reads one line from it. print() writes text to standard output. A stream is simply a flow of data that a program can read or write. Keeping conversion separate makes the program easier to test later.
Try these problems on this page. First write the sample conversation, then write the program.
- Read a name and greet the user.
- Read two numbers and print their sum in a sentence.
- Print a date using
sep. - Create a formatted product receipt.
- Read hours and hourly rate and print salary.
- Predict the output of small programs using
sepandend. - Build a temperature conversion prompt and result.
- Print a three-column table using f-strings.
- Create an invoice with aligned labels.
- Design the input and output for a menu item order before writing code.
Show hints
- Store
input()in a variable and use an f-string. - Convert both inputs to numbers.
- Pass the date pieces to
print()withsep="-". - Give every value a label.
- Multiply hours by the hourly rate.
sepgoes between values;endreplaces the final newline.- Convert the temperature to
float. - Use alignment such as
:<12and:>8. - Print one label and value per line.
- Write example input and output before coding.
Show solution ideas
name = input("Name: ")followed byprint(f"Hello, {name}!").- Convert with
int()and calculatefirst + second. print(year, month, day, sep="-").- Use quantity times unit price and format money with
.2f. salary = float(hours) * float(rate).- Read the code left to right and mark each separator and ending character.
- Use
fahrenheit = celsius * 9 / 5 + 32. - Use f-string width specifiers.
- Separate input, calculation, and display with clear labels.
- Decide the prompt, type, and output for every field.
Create a formatted travel booking confirmation that accepts a passenger name, destination, ticket count, and total price.
Build a program that reads a product name, quantity, and price and prints a formatted receipt line.