PyPython Lab

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

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

  1. Line 1: create the variable ten holding the string "Lan".
  2. Line 2: create the variable tuoi holding the integer 15.
  3. Line 3: take the old value 15, add 1, and assign it back into tuoi; now tuoi is 16.
  4. Line 4: print the values, separated by spaces.
  5. 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

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