Stage 1 · 20 minutes · Free
Reading input with input()
Read what the user types with input(), convert strings to numbers with int() and float(), and division / and //.
Objectives
- Read data with input()
- Convert types with int(), float(), str()
- Understand the difference between /, // and %
Why learn this
A useful program must take data from the user: enter a name, a score, an amount of money. input() does this.
Concept
input() reads one line the user types and ALWAYS returns a string (str), even when they type a number.
To compute, convert to a number: int(input()) for integers, float(input()) for real numbers.
Division / always gives a float (7 / 2 = 3.5, 6 / 2 = 3.0). // is floor division (7 // 2 = 3), % is the remainder (7 % 2 = 1).
On Python Lab, input data comes from the "Input data" box, one line per input() call.
Syntax
ten = input()
n = int(input())
x = float(input())
Example
a = int(input())
b = int(input())
print("Tổng:", a + b)
print("Thương:", a / b)
print("Dư:", a % b)Input data:
7 2
Output:
Tổng: 9 Thương: 3.5 Dư: 1
Line-by-line walkthrough
- Line 1: read the first line "7", convert it to the number 7, assign to a.
- Line 2: read the second line "2", convert it to the number 2.
- Line 3: 7 + 2 = 9.
- Line 4: 7 / 2 = 3.5 (always a real number).
- Line 5: 7 divided by 2 leaves remainder 1.
Common mistakes
a = input()
print(a + 1)a is a string, it cannot be added to a number: TypeError.
a = int(input())a = input()
b = input()
print(a + b) # nhập 2 và 3Adding two strings concatenates them, printing 23 instead of 5.
Dùng int(input()) cho cả hai.n = int(input()) # người dùng gõ 2.5int() cannot convert a string with a dot: ValueError.
Dùng float(input()) khi dữ liệu có thể là số thực.Summary
- input() always returns a string.
- int(), float() convert strings to numbers.
- / gives a real number, // gives the integer part, % gives the remainder.
Write code right in the browser; the grader runs real Python and points to the exact wrong line.
Practice free