Stage 1 · 20 minutes · Free
Variables and data types
What a variable is, how to name variables, the four basic data types int, float, str, bool, and the type() function.
Objectives
- Create variables and assign values
- Tell int, float, str, bool apart
- Use type() to see a type
- Name variables by the rules
Why learn this
A program needs to remember information: a user name, a score, a price. A variable is a 'labelled box' for storing and retrieving that information.
Concept
Write ten_bien = gia_tri to create a variable. The = in Python means assignment (storing a value in the box), not 'equals'.
Four basic types: int is an integer (10, -3), float is a real number (3.14, 5.0), str is a text string ("Lan"), bool is true/false (True, False).
A variable name contains letters, digits and _, does not start with a digit, and has no spaces. Use meaningful names like diem_toan instead of x.
Assigning a new value replaces the old one.
Syntax
ten = "Lan"
tuoi = 15
chieu_cao = 1.55
da_dang_ky = True
print(type(tuoi))
Example
ten = "Lan"
tuoi = 15
tuoi = tuoi + 1
print(ten, "năm sau", tuoi, "tuổi")
print(type(ten))Output:
Lan năm sau 16 tuổi <class 'str'>
Line-by-line walkthrough
- Line 1: create the variable ten holding the string "Lan".
- Line 2: create the variable tuoi holding the integer 15.
- Line 3: take the old value 15, add 1, and assign it back into tuoi; now tuoi is 16.
- Line 4: print the values, separated by spaces.
- Line 5: type(ten) tells you ten has type str.
Common mistakes
2ten = "Lan"A variable name cannot start with a digit.
ten2 = "Lan"ho ten = "Lan"A variable name has no spaces.
ho_ten = "Lan"print(Tuoi)You created tuoi (lowercase) but called Tuoi: Python reports NameError.
print(tuoi)Summary
- = is assignment.
- int, float, str, bool are the 4 basic types.
- type() tells you the type of a value.
- Variable names are case-sensitive, so pick meaningful names.
Write code right in the browser; the grader runs real Python and points to the exact wrong line.
Practice free