LESSON 02 · BEGINNER PATH13 min

Variables and Types

A variable is a name that refers to a value. Assign a value with =, then use the name in later expressions. Python determines the type from the value you assign.

Store values in variables and distinguish common Python data types.

Before you start: Hello, World!

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: Variables and Types

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    A useful program remembers information instead of typing the same values again and again. In Python, a variable is a name that refers to a value. On the lesson page, our starting program stores a learner's name, the number of lessons finished, a progress value, and a true-or-false value for whether learning is under way. Before running it, sort the four values in your head. Which one is text, which ones are numbers, and which one describes a yes-or-no state? Notice that the name of a variable is chosen by the programmer, while the type belongs to the value currently stored under that name. By the end, you will be able to inspect those types, explain what a second assignment does, and convert between text and numbers when the task calls for it.

  2. 00:47

    Open the editor, read the assignments from top to bottom, then predict the first printed line. Doing that before we press Run makes the output a test of your understanding rather than a surprise to memorize. Read an equals sign in an assignment as put this value under this name, not as a claim that both sides will always be equal. The quoted name Maya is a string. The count three is an integer, a whole number. The progress value zero point five is a float, a number with a decimal point. True is a Boolean value and must have a capital first letter in Python. The starter prints the learner and lesson count, separated by a space.

  3. 01:28

    Then it calls type on two values and displays each type's name, so you see float and bool. Python knows their types from the values; there is no separate declaration in this beginner example. Now consider the guide example with points. Points starts at ten. The next assignment uses the current value of points plus five, so points becomes fifteen. A final plus-equals two updates it to seventeen. The name did not become a permanent box holding ten; it now refers to the latest result. This also means the right-hand side is evaluated before the new assignment takes effect. When you see points equals points plus five, use the old points value to calculate fifteen, then update the name.

  4. 02:13

    If you reverse that order in your mental model, the line seems impossible. A short trace table with the line number and the current value of points is a useful debugging tool. It is especially helpful when a program makes several changes to the same name. Pause before each print and predict fifteen, then seventeen. The next example starts with raw equal to the string twelve. Converting raw with int and adding three produces fifteen. Joining raw with the string three produces the text one two three, displayed as 123. Those are different operations even though the characters look like numbers. The final print confirms that raw remains a string; calling int on it did not overwrite the original name.

  5. 03:00

    The Boolean guide example reveals another subtlety. bool of an empty string is False, but bool of the nonempty string containing the word False is True. That conversion checks whether the string is empty, not whether it spells a Boolean word. If you need to interpret an answer such as yes, compare normalized text explicitly. The example lowers the answer and compares it with yes, producing True. These small distinctions matter whenever a program reads input from a form or command line, because input arrives as text and must be interpreted according to your actual rules. Let us make two mistakes on purpose. First, assign a value to lowercase name and then try to print capitalized Name.

  6. 03:45

    Python treats those as different identifiers and raises NameError. Fix the spelling where the name is used. This is why a clear, consistent style is more than decoration. Second, write a message by adding quoted text to the integer twelve. Python raises TypeError because string concatenation and numeric addition are different operations. If the goal is a message, convert the number with str or put it in an f-string. If the goal is arithmetic, convert suitable numeric text with int before adding. Do not silence the error by randomly adding quotes; decide what kind of result you need. A quick diagnostic is to print type of each value just before the failing operation.

  7. 04:30

    Once the types are visible, the needed conversion is often obvious. Your practical task is to create a variable named next_lesson with the numeric value four. Use the existing learner name and the new lesson number in one printed sentence. The checker looks for both the value and a line containing the name and the number, so make the output easy for a human to read too. Before you run, predict whether next_lesson is an integer or a string. If you write the four inside quotes, you have text instead of the requested number. If you print the learner name and the lesson number on separate lines, the combined sentence is missing.

  8. 05:10

    Run the program, inspect the output, and use the task checker to confirm the behavior. Then try changing learner from Maya to your own name. A good program should update its message from the variable instead of making you edit the same name in several places. The quiz asks about a decimal value's type, converting five to text, and what happens when a name is assigned a new value of another type. Predict each answer first, and use the console if you need evidence. In the next lesson, we will put several related values into one ordered list and learn how a single variable can refer to that collection.

Understand the concept

Beginners commonly use integers, floating-point numbers, strings, and booleans. Use type() to inspect a value, and int(), float(), or str() when an explicit conversion is needed.

  • Assignment uses =
  • int, float, str, and bool
  • Convert types explicitly

See it step by step

Read the code, predict the output, then compare it with the result.

01. Store and display values

PYTHON
learner = "Sam"
completed = 4
print(learner, completed)
EXPECTED OUTPUT
Sam 4

Assignment gives the values names. print() can display two values separated by a space.

02. Inspect two types

PYTHON
score = 8.5
ready = True
print(type(score).__name__)
print(type(ready).__name__)
EXPECTED OUTPUT
float
bool

A decimal value is a float; True is a bool. type(...).__name__ shows each type's name.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

Trace a name through several assignments

Think of a variable as a label that points to a current value. Assignment evaluates the expression on the right before connecting the name on the left to its result. Reusing the same name does not edit the old integer in place: the name simply refers to the newly calculated value afterward.

This explains why a running total works. Start with an amount, add a new contribution, and use the updated value in the next step. Trace the value of points after every line before you run the example. Then change the added contribution from 5 to 8 and predict the two displayed totals.

PYTHON
points = 10
points = points + 5
print(points)
points += 2
print(points)
EXPECTED OUTPUT
15
17
Follow the reasoning
  1. The right side points + 5 uses the current value 10.
  2. The second assignment reconnects points to 15.
  3. += 2 is a shorter way to calculate and assign the next total.
02 / 03

A numeric-looking string is still text

Data read from a text field or a file often arrives as a string, even when its characters look like digits. Python does not silently guess whether you mean arithmetic or text joining. Adding a number to a string requires conversion; adding two strings joins their characters instead of their numeric values.

Here raw remains unchanged when int(raw) makes an integer for one expression. Compare the arithmetic result with the joined string and consider which one a checkout total would need. Before converting real input, make sure it contains a valid number: int('twelve') raises ValueError rather than inventing a value.

PYTHON
raw = "12"
print(int(raw) + 3)
print(raw + "3")
print(type(raw).__name__)
EXPECTED OUTPUT
15
123
str
Follow the reasoning
  1. int(raw) creates the integer 12 for arithmetic.
  2. raw + '3' joins two strings to produce '123'.
  3. The original raw value is still a str.
03 / 03

Booleans are not words saying true or false

A Boolean value is either True or False. A string containing the letters 'False' is a different kind of value: it is nonempty text. Converting that text with bool asks whether it is empty, not whether its spelling matches the Boolean word. This matters when form answers or configuration values arrive as text.

The example contrasts an empty string, a nonempty string, and a real Boolean. A program that accepts yes/no text should explicitly compare normalized input with an allowed word instead of relying on bool(text). Try changing the answer to 'YES' and decide whether the comparison should still be considered true; lower() handles that case.

PYTHON
print(bool(""))
print(bool("False"))
answer = "yes"
print(answer.lower() == "yes")
EXPECTED OUTPUT
False
True
True
Follow the reasoning
  1. Empty text is false in a Boolean context; nonempty text is true.
  2. The string 'False' is not the Boolean value False.
  3. An explicit text comparison checks the intended answer.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnCreate a variable named next_lesson with the number 4. Print a sentence that includes the learner's name and that number.
Need a hint?

Assign next_lesson = 4. Then print a line that uses both learner and next_lesson; print(learner, 'starts lesson', next_lesson) is one valid shape.

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.What is the type of 4.0?

    02.What does str(5) produce?

    03.After x = 2 and x = "two", what is the type of x?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Case-sensitive names

    COMMON MISTAKE
    name = "Maya"
    print(Name)
    FIX
    name = "Maya"
    print(name)

    What happens: NameError because Name and name are different names.
    Use exactly the same spelling and capitalization each time.

    Mixing text and numbers

    COMMON MISTAKE
    age = 12
    print("Age: " + age)
    FIX
    age = 12
    print("Age: " + str(age))

    What happens: TypeError when joining a string and an integer.
    Convert the number to a string before concatenating it with text.

    Browse this lesson’s problem fixes