PyPython Lab

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

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

  1. Line 1: read the first line "7", convert it to the number 7, assign to a.
  2. Line 2: read the second line "2", convert it to the number 2.
  3. Line 3: 7 + 2 = 9.
  4. Line 4: 7 / 2 = 3.5 (always a real number).
  5. 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à 3

Adding 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.5

int() cannot convert a string with a dot: ValueError.

Dùng float(input()) khi dữ liệu có thể là số thực.

Summary

Practice 2 exercises and 3 quick questions

Write code right in the browser; the grader runs real Python and points to the exact wrong line.

Practice free