Python Lab

Stage 1 · 20 min · 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

Why learn this

Programs need to remember information: a user's name, a score, a price. A variable is a "labelled box" to store that information and get it back.

Concept

Write variable_name = value to create a variable. In Python, = means assignment (putting a value in the box), not "is equal to".

The four basic types: int is a whole number (10, -3), float is a decimal number (3.14, 5.0), str is text ("Lan"), bool is true/false (True, False).

Variable names contain letters, digits and _, can't start with a digit and have no spaces. Prefer meaningful names like math_score 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 explanation

  1. Line 1: creates the variable ten holding the string "Lan".
  2. Line 2: creates the variable tuoi holding the integer 15.
  3. Line 3: takes the old value 15, adds 1 and assigns it back to tuoi, so tuoi is now 16.
  4. Line 4: prints the values, separated by spaces.
  5. Line 5: type(ten) tells you that ten is a str.

Common mistakes

2ten = "Lan"

Variable names can't start with a digit.

ten2 = "Lan"
ho ten = "Lan"

Variable names can't contain spaces.

ho_ten = "Lan"
print(Tuoi)

You created tuoi (lowercase) but used Tuoi: Python raises NameError.

print(tuoi)

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