Python & data · Lesson 03
Variables and data types
Store values, inspect common types, and distinguish a number from text.
- Assign and update names
- Recognize strings, integers, floats, and booleans
- Convert between compatible values
Helpful background: You can run a small Python program.
Assign a value to a name
Assignment connects a name to a value. Names can contain letters, digits, and underscores, but cannot begin with a digit. Python is case-sensitive: score and Score are different names.
Use descriptive names. Assigning a new value to a name changes what that name refers to.
visitors = 12
visitors = visitors + 3
print(visitors) # 15Common built-in types
An int is a whole number, a float represents a floating-point number, a str holds text, and a bool is either True or False. type() tells you the type of a value.
Quotation marks matter: 12 is an integer, while "12" is a string. They are different values even though they may look similar when printed.
count = 12
price = 3.5
name = "Mira"
is_open = True
print(type(count))
print(type(name))Convert deliberately
Functions such as int(), float(), and str() convert compatible values. Conversions can fail: int("twelve") raises ValueError because that text is not a valid integer.
Floating-point arithmetic can have small rounding effects. For money, consider decimal.Decimal rather than assuming a float is exact.
count_text = "12"
count = int(count_text)
print(count + 1) # 13
print(str(count) + " visitors")Choose clear names
Use lowercase words separated by underscores, such as visitor_count. Avoid names that hide meaning or reuse built-ins such as list, str, and sum.
A comment starts with # and is ignored by Python. Comments are useful for explaining why a decision was made.
What is the result of int("12") + 1?
Your turn
Store a book title and a page count, then print a sentence containing both.
title = "The River" pages = 120 print(f"{title} has {pages} pages.")
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited