Variables and Data Types

Published by Brayan K

A variable in Python is a named container that stores a value in your program's memory, letting you label data and reuse or change it as the code runs.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A name for a value

Write a name, an equals sign and a value, and Python remembers the value under that name. Wherever the name appears afterwards, Python uses the value:

price = 250
quantity = 3
print(price * quantity)
print(price)

# ✅ Expected output:
# 750
# 250

Here the equals sign doesn't mean "is equal to". It's an instruction: work out the right-hand side, then attach the name on the left to the result. That's why the right-hand side can be a calculation: total = price * quantity keeps the answer, not the sum. Asking whether two values are equal is a different operator, ==, in Operators and Expressions.

Changing a variable

Assign to the same name again and it refers to the new value; the old one is forgotten. The new value can be worked out from the old one, because the right-hand side runs first:

score = 10
print(score)
score = score + 5
print(score)
score = 0
print(score)

# ✅ Expected output:
# 10
# 15
# 0

Read score = score + 5 as: take the current score, add 5, and attach the name to the result. The shorter score += 5 does the same; it's covered with the other assignment operators in Operators and Expressions.

Two names for one value

Assigning one variable to another copies nothing: both names now refer to the same value. Giving a a new value afterwards moves only a, and b stays where it was:

a = 5
b = a
a = 6
print(a, b)

# ✅ Expected output:
# 6 5

For numbers and text that's the whole story, because they can't be changed in place, only replaced. A list can be changed in place, so two names sharing one list both see the change; Lists and Collections shows when that matters.

Rules for names

A name can contain letters, digits and underscores. It can't start with a digit, can't contain spaces or hyphens, and can't be one of Python's keywords, such as class, if or for. Each broken rule is a SyntaxError, so the program stops before any of it runs.

A digit first makes Python read the start of the name as a number:

2nd_place = "Ada"

# ✅ Expected error:
# SyntaxError: invalid decimal literal

A hyphen is a minus sign, so this asks Python to store a value in "my minus name":

my-name = "Ada"

# ✅ Expected error:
# SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

Keywords are reserved for Python's own syntax:

class = "A"

# ✅ Expected error:
# SyntaxError: invalid syntax

Names are case-sensitive, so age and Age are two separate variables:

age = 30
Age = 40
print(age, Age)

# ✅ Expected output:
# 30 40

By convention, Python names are lowercase words joined by underscores, like max_score, and a value that should never change gets a name in capitals, like TAX_RATE = 0.2. Python enforces neither convention; both tell people reading the code what you meant.

Don't reuse a built-in function's name

print, str, int, input and type are names too, for functions Python provides. Nothing stops you assigning to one, but from then on the name refers to your value and the function is out of reach:

str = "hello"
print(str(5))

# ✅ Expected error:
# TypeError: 'str' object is not callable

"Not callable" means the code put () after something that isn't a function, here the text "hello". Pick a name that says what the value is, such as greeting, and the function stays available.

Using a name before it exists

A name exists only once the line that assigns it has run. Python reads from the top, so this program asks for total one line too early:

print(total)
total = 10

# ✅ Expected error:
# NameError: name 'total' is not defined

Swap the two lines and the program works. A misspelt name gives the same NameError.

Every value has a type

Python keeps track of what kind of value each one is. The four you'll use most are str for text, int for whole numbers, float for numbers with a decimal point and bool for True and False. type() tells you which one a value is:

print(type("Ada"))
print(type(42))
print(type(3.5))
print(type(True))
print(type("42"))

# ✅ Expected output:
# <class 'str'>
# <class 'int'>
# <class 'float'>
# <class 'bool'>
# <class 'str'>

The last one is text, because of the quotes. True and False need their capital letters: lowercase true is just a name that doesn't exist, and Python stops with a NameError.

The type belongs to the value, not to the name, so one name can refer to different kinds of value in turn:

thing = 5
print(type(thing))
thing = "five"
print(type(thing))

# ✅ Expected output:
# <class 'int'>
# <class 'str'>

Converting between types

int(), float(), str() and bool() each make a value of their own type from another value. Three of these results surprise most people:

print(int("42") + 1)
print(float("3.5") * 2)
print(str(250) + "p")
print(int(3.9))
print(int(-3.9))
print(int(float("3.5")))
print(bool("False"))
print(bool(""))

# ✅ Expected output:
# 43
# 7.0
# 250p
# 3
# -3
# 3
# True
# False

int() drops the decimal part rather than rounding, so 3.9 becomes 3 and -3.9 becomes -3. And bool() of text is False only for empty text: the word "False" is still text that isn't empty, so it converts to True.

int() reads only whole numbers from text, so text with a decimal point stops the program. Converting to a float first, as in the sixth line above, avoids it:

print(int("3.5"))

# ✅ Expected error:
# ValueError: invalid literal for int() with base 10: '3.5'

Whatever input() returns is text, so a number typed by the user needs one of these conversions before you do arithmetic with it.

Several names at once, and swapping

Put several names on the left and the same number of values on the right, and each name gets the value in its position. Python builds the whole right-hand side before handing anything out, which is what makes the one-line swap work:

x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)

# ✅ Expected output:
# 1 2
# 2 1

The counts on both sides have to match. Three values for two names stops with a ValueError, too many values to unpack, and two values for three names stops like this:

a, b, c = 1, 2

# ✅ Expected error:
# ValueError: not enough values to unpack (expected 3, got 2)

Practice: swap and convert

Replace the three blanks, in order, with the values in the hint lines, so that the two drinks trade places and the text "3" becomes a number you can double.

first = "tea"
second = "coffee"
first, second = ___, ___
cups = ___("3")
print(first, second, cups * 2)

# 👉 replace ___ with second
# 👉 replace ___ with first
# 👉 replace ___ with int

# ✅ Expected output:
# coffee tea 6

On your own: a shopping total

A shop sends you the price as text, price = "1.50", and the quantity as a number, quantity = 4. Write a program that prints what the four items cost, then compare it with this solution:

price = "1.50"
quantity = 4
total = float(price) * quantity
print(total)

# ✅ Expected output:
# 6.0

Practice quiz

After a = 5, then b = a, then a = 6, what is b?

  • 6
  • 5
  • 11
  • An error

Answer: 5. b = a ties b to the value 5. Giving a a new value later doesn't move b.

What does print(int(-3.9)) show?

  • -3
  • -4
  • 3
  • -3.9

Answer: -3. int() drops the decimal part instead of rounding, for negative numbers too.

Which of these is a valid variable name?

  • 2nd_place
  • my-name
  • _total
  • class

Answer: _total. A name may start with a letter or an underscore. A digit first, a hyphen and a keyword are all syntax errors.

What does print(bool("False")) show?

  • False
  • An error
  • None
  • True

Answer: True. Any text that isn't empty counts as True, whatever the words say.

What happens when Python runs int("3.5")?

  • It gives 3
  • It gives 4
  • It stops with a ValueError
  • It gives 3.5

Answer: It stops with a ValueError. int() reads only whole numbers from text. int(float("3.5")) gives 3.

x, y = 1, 2 is followed by x, y = y, x. What is x now?

  • 1
  • 2
  • 3
  • An error

Answer: 2. The right-hand side is built first, as 2 and 1, and then handed out, so the values swap.

After str = "hi", what does str(5) do?

  • Stops with TypeError: 'str' object is not callable
  • Gives '5'
  • Gives hi5
  • Gives 5

Answer: Stops with TypeError: 'str' object is not callable. The name str now refers to the text "hi", so the str() function can no longer be reached by that name.

What does print(type("42")) show?

  • <class 'int'>
  • <class 'str'>
  • <class 'float'>
  • 42

Answer: <class 'str'>. Quotes make 42 text, even though its characters are digits. Converting it with int() would make an integer.

Continue this course

Frequently asked questions

Can a variable name use letters from other languages?

Yes. Python 3 accepts letters from any alphabet, so café = 3 and π = 3.14 are valid names. If other people will work on your code, plain English letters are kinder, because not every keyboard can type the others.

Is there a limit on how long a variable name can be?

Not a practical one. Choose names that say what the value is, like total_price, over names that only save typing.

Related lessons