Python Lab

Stage 1 · 20 min · Free

Reading input with input()

Read what the user types with input(), convert strings to numbers with int() and float(), and the / and // operators.

Objectives

Why learn this

A useful program has to take data from the user: a name, a score, an amount of money. input() does that.

Concept

input() reads one line the user types and ALWAYS returns a string (str), even if they typed a number.

To calculate, convert it to a number: int(input()) for whole numbers, float(input()) for decimals.

Division / always gives a float (7 / 2 = 3.5, 6 / 2 = 3.0). // gives the whole-number part (7 // 2 = 3), and % gives the remainder (7 % 2 = 1).

On Python Lab, input comes from the "Input" box; each line is one 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:

7
2

Output:

Tổng: 9
Thương: 3.5
Dư: 1

Line-by-line explanation

  1. Line 1: reads the first line "7", converts it to the number 7 and assigns it to a.
  2. Line 2: reads the second line "2" and converts it to the number 2.
  3. Line 3: 7 + 2 = 9.
  4. Line 4: 7 / 2 = 3.5 (always a float).
  5. Line 5: 7 divided by 2 leaves remainder 1.

Common mistakes

a = input()
print(a + 1)

a is a string and can't be added to a number: TypeError.

a = int(input())
a = input()
b = input()
print(a + b)  # nhập 2 và 3

Adding two strings joins them, so it prints 23, not 5.

Dùng int(input()) cho cả hai.
n = int(input())  # người dùng gõ 2.5

int() can't convert a string with a decimal point: ValueError.

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

Summary

2 practice tasks and 3 quiz questions

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

Practice for free