Course contentsLesson 3 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 03

Variables and data types

Edit lesson

Store values, inspect common types, and distinguish a number from text.

15 minProgress saves on this device
In this lesson
  • 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.

Assignmentpython
visitors = 12
visitors = visitors + 3
print(visitors)  # 15

Common 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.

Inspect valuespython
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.

Convert a valuepython
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.

Knowledge check

What is the result of int("12") + 1?

Try first; feedback appears after you check.
Apply it

Your turn

Store a book title and a page count, then print a sentence containing both.

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson