03: Input și Output
Make programs interactive with input() and format output with print().
Lesson 03 · Input and Output¶
What you'll learn
- How to read data from the user with
input() - Why
input()always returnsstr - How to convert input into numbers
- Advanced output formatting
The input() function¶
input() pauses the program and waits for the user to type something and press Enter:
Run:
The text inside the parentheses is the prompt — the message shown to the user.
input() ALWAYS returns str¶
This is the most common source of errors for beginners:
Even if the user types 14, Python receives the string "14", not the number 14.
Converting input¶
If the user types something else
int(input(...)) will raise an error if the user types text instead of a number. We'll solve that in the lesson on conditions and exceptions.
The print() function — details¶
The sep separator¶
print("Mon", "Tue", "Wed") # Mon Tue Wed
print("Mon", "Tue", "Wed", sep=", ") # Mon, Tue, Wed
print("Mon", "Tue", "Wed", sep="\n") # each on a new line
The end terminator¶
Empty line¶
Combined examples¶
Simple greeting program¶
first_name = input("Your first name: ")
age = int(input("Your age: "))
print()
print(f"Hello, {first_name}!")
print(f"Next year you will be {age + 1} years old.")
Reading multiple values¶
a = float(input("First number: "))
b = float(input("Second number: "))
print(f"{a} + {b} = {a + b}")
print(f"{a} × {b} = {a * b}")
Exercises¶
Exercise 1 — Personalized greeting¶
Write a program that asks for name and age, then displays: "Hi, [name]! You are [age] years old."
Solution
Exercise 2 — Rectangle area¶
Ask for the length and width of a rectangle, calculate the area and the perimeter.
Solution
Exercise 3 — How many seconds?¶
Ask for hours and minutes, display the total in seconds.
Solution
Mini-project: Interactive calculator¶
Write a program that asks for two numbers and displays all the basic operations.
Example run:
First number: 10
Second number: 3
10.0 + 3.0 = 13.0
10.0 - 3.0 = 7.0
10.0 × 3.0 = 30.0
10.0 / 3.0 = 3.3333333333333335
10.0 // 3.0 = 3.0
10.0 % 3.0 = 1.0
10.0 ^ 3.0 = 1000.0
Solution
Summary¶
input("message")reads text from the keyboard — ALWAYS returnsstr- Convert with
int(input(...))orfloat(input(...)) print(a, b, sep=", ")controls the separatorprint("text", end="")controls what comes after the line
Next step: → Lesson 04: Conditions