Coding Tutorials

Python variables and data types, plainly explained

Flat illustration of labelled boxes holding numbers, text and true or false values, for Python variables

A variable in Python is a name that holds a value, so a program can use that value later without typing it again. You create a variable by writing a name, an equals sign, and a value. Python then stores the value under that name, and every later use of the name refers to the stored value.

The data type is the kind of value stored. A whole number, a decimal number, a piece of text, and a true or false value are different types, and Python treats them differently. That difference matters when you add, compare, or print values, because an operation that works for numbers may not work for text. If you are coming from the first program guide, this is the step that turns a fixed print line into a program that can work with changing values.

Assign a value and use the name

The examples below create four variables and then print them. Read each assignment from right to left in your head: the value on the right is stored under the name on the left. The print lines then show the stored values, which proves the names are holding what you assigned.

name = "Sara"
age = 29
height = 1.68
is_student = True

print(name)
print(age)
print(height)
print(is_student)

You can change a variable by assigning a new value to the same name. The old value is replaced, and later lines see only the new value. That is useful for a score that goes up, a total that grows, or a message that changes as a program runs. It also means order matters: a print line shows the value at the point where it runs, not the value the name will hold later.

score = 0
print(score)
score = 10
print(score)

The main types, side by side

The table below lists the types used most often at the start, with an example of each and a note on what it is for. The official Python docs describe these as built in types, and the docs pages for numbers, text, and truth values are the reference behind this table. Lists and dictionaries are separate types with their own guides later in this series, so they are not covered in depth here.

Type nameExampleUsed for
int42Whole numbers, such as counts and ages
float1.68Numbers with a decimal part, such as measurements
str"Sara"Text, such as names and messages
boolTrueTrue or false values, such as a yes or no flag
NoneTypeNoneNo value, such as a result that has not been set yet

You can ask Python for the type of a value with the type function. That is a useful check when a result looks wrong, because it tells you whether a value is text when you expected a number, or the other way round. Use it while learning, and remove it from a finished program once the types are clear.

print(type(42))
print(type("Sara"))
print(type(True))

Work with numbers and text

Numbers support arithmetic in the way you would expect. Addition, subtraction, multiplication, and division use the usual symbols, and the result keeps the type that makes sense for the operation. Dividing two whole numbers gives a decimal result, even when the division comes out even, and that is a detail worth checking when you print a result and see a decimal point you did not expect.

total = 20 + 5
price = 12.50 + 3.50
average = 30 / 4
print(total)
print(price)
print(average)

Text supports joining and repeating, but not arithmetic in the number sense. Joining two pieces of text with a plus sign gives one longer piece of text. Repeating text with a multiplication sign gives the text repeated that many times. Both are useful for building messages, and both are different from adding numbers, even though they share a symbol.

greeting = "Hello, " + "Sara"
stars = "*" * 5
print(greeting)
print(stars)

To build a message that mixes text and a number, convert the number to text first, or let print handle separate values. The second approach is simpler at the start: print takes values separated by commas and shows them with a space between them. The first approach uses the str function to turn a number into text, then joins the pieces. Both give a readable message, and the choice is about what is easier to read in that part of the program.

age = 29
print("Age:", age)
message = "Age: " + str(age)
print(message)

Once values can be stored, the next useful skill is making a program choose. Conditions in Python use true or false values to pick a path, and loops in Python repeat a block while a value meets a test. If you have not yet run a program at all, start with your first Python program and come back here once print works.

Common mistakes to watch for

Using an equals sign where a comparison is meant is a mistake that shows up later with conditions, but it starts here. A single equals sign assigns a value, while two equals signs compare two values. Writing one when you mean the other either changes a variable by accident or fails to test anything, so check which one you meant whenever a result looks wrong.

Spelling a variable name differently in two places creates a new name instead of an error at the point of typing, and Python then reports the second spelling as unknown when it runs. Variable names are case sensitive, so score, Score, and SCORE are three different names. Pick one spelling, use it everywhere, and use lower case names with underscores for multi word names, which is the style the Python docs and most Python code follow.

Forgetting quotes around text is another early mistake. Without quotes, Python reads the text as a name or as code, and it reports an error if that name was never defined. With quotes in the wrong place, part of the text can leak out and break the line. Read the line aloud: the text you want to store should sit fully inside one pair of matching quotes.

Mixing a number and text in one addition is a type error, not a spelling error. Python raises a TypeError and names the types involved, which tells you exactly what to convert. Do not guess at a fix by adding quotes around everything, because that turns numbers into text and breaks later arithmetic. Convert only the value that needs to be text, or keep the values separate in the print call.

Limits of this guide

This guide covers basic types and simple operations. It does not cover lists, dictionaries, sets, or custom classes, which are covered in later guides in this series. It also does not cover how numbers are stored in memory, how text encoding works in depth, or how to handle money with exact decimal arithmetic, all of which matter in larger programs but would distract from the basics here. A later guide on files and input will cover converting text input to numbers safely, including what to do when the input is not a number at all.

Worked example: a small price calculation

Variables earn their keep when a program reuses a value in several places. The example below stores a price, a quantity, and a tax rate, then builds a total from them. Changing the price in one place changes the total everywhere it is used, which is the point of giving a value a name instead of typing the number again in each line.

price = 12
quantity = 3
tax_rate = 0.2
subtotal = price * quantity
total = subtotal + subtotal * tax_rate
print("Total:", total)

Read the calculation from the top down. The subtotal line multiplies price by quantity, and the total line adds tax based on that subtotal. Each line uses only values created above it, so the order of the lines is part of the logic. Moving the total line above the subtotal line would fail, because subtotal would not exist yet at that point.

Try changing one value and running the program again. Change quantity to 4, and the subtotal and total should both change, while the maths lines stay the same. That test shows the difference between a value and a formula. Values sit in variables, formulas sit in the lines that combine them, and a good program keeps those two jobs separate.

Types in a table, with what each one suits

The main built-in types cover numbers, text, true or false values, and the absence of a value. The table below gives a plain description of each one and a typical use, so the choice of type can follow the job rather than habit. A price with cents needs a decimal type, a count needs a whole number, and a name needs text, and those choices shape what the program can safely do with each value.

TypeExample valueTypical use
int42Counts, ages in whole years, quantities
float12.5Prices, measurements, averages
str"Maya"Names, messages, labels
boolTrueA setting switched on or off, a test result
NoneTypeNoneA value deliberately left empty for now

Notice that True and False start with a capital letter in Python, while true and false in lower case are treated as ordinary names and will cause an error when they have not been defined. That capital letter is part of the value itself, and it is one of the small spelling rules worth learning by typing the examples rather than only reading them.

When a type is unclear, the type function shows it. Print type of a variable while learning, and compare the result with the type expected. That check turns a vague feeling that something is wrong into a concrete fact, such as discovering that a value is text when the program needs a number.

Reassigning a name, and why it confuses readers

Python lets one name hold a new value later in the program, and it lets that new value be of a different type. The example below starts with a count and later replaces it with a message, which is allowed, yet it makes the program harder to follow. A reader who sees the name later cannot tell from the name alone which kind of value it holds at that point.

count = 5
print(count)
count = "five"
print(count)

A clearer habit is to give each job its own name, and to keep the type of a name stable through a short program. Use count for the number and count_text for the message, and the reader never has to guess. That habit costs nothing in a small program and saves real confusion in a longer one, where a name may be used many lines after it was last set.

Reassignment is still useful when a value genuinely changes, such as a running total that grows in a loop. In that case the name keeps the same type, and the change is the point of the variable. The rule to keep is simple. Reassign when the value changes, and choose a new name when the meaning changes.

Converting between types on purpose

Conversion functions turn one type into another, and they are used when input or a calculation gives the wrong type for the next step. The int function turns text like "42" into the number 42, float turns text like "12.5" into a decimal, and str turns a number into text for a message. Each conversion returns a new value, so the result must be stored or used directly, or the conversion has no effect.

text_count = "7"
count = int(text_count)
print(count + 3)

Conversion can fail when the text does not look like the target type. Trying int on "seven" raises an error, because there is no number hidden in that word. That error is a useful signal. It says the input was not in the form the program expected, and the fix belongs at the point where the input is checked, rather than in the maths that follows.

For money and measurements, remember that float values are stored in binary form, so some decimal values cannot be represented exactly. That detail rarely matters in a beginner program that prints a total, yet it is the reason a program that must track money exactly uses a dedicated decimal type in real projects. For learning, the point is to know that float is an approximation, and to avoid testing float values for exact equality after several steps of maths.

Frequently asked questions

Do I have to declare a variable type in Python?

No. You assign a value, and Python works out the type from that value. The same name can later hold a different type, but doing that in one program can confuse readers, so keep a name on one kind of value where you can.

Why does adding a number and text fail?

Python does not guess how to combine different types. A number plus text has no single obvious result, so Python raises a TypeError. Convert the number to text first if you want to join them, or keep them as separate values.

What is None used for?

None means no value yet, or no result to return. It is different from zero and from an empty string. Code often checks for None before using a value that may not have been set.

How do I check the type of a variable?

Use the type function and print its result while learning, for example print(type(price)). The result shows the type name, which helps when a value behaves like text yet the program expected a number.

Can a variable change type in Python?

Yes, a name can be reassigned to a value of a different type, because Python does not fix a type to a name. Keeping one type per name in a short program is still clearer, so a reader can tell what kind of value a name holds.

When should I use float instead of int for a number?

Use float when the value needs a fractional part, such as a price with cents or a measurement. Use int for counts and quantities that are whole by nature, because a whole number type keeps the meaning of the value clear.

Sources