Variables and Data Types in Python

By the Syncfusion DevTutorials team · Last updated

How to store a value in a name, the kinds of value Python works with, how to check and convert between them, and why indentation changes what a program does.

Think about a school bag with labelled pockets.

One pocket holds your lunch. One holds your pencil box. One holds your library card.

You do not have to remember where everything is. You just read the labels.

A program needs the same thing. It holds many pieces of information at once: a name, a mark, a date, an answer to a question. Without labels, none of it can be found again.

Python gives you labels. A label with a value attached is called a variable.

What You Will Learn

In this lesson, you will learn:

  • How to create a variable, change it, and remove it
  • How to give several variables values in one line
  • What a constant is, and why Python uses capital letters for one
  • The main kinds of value Python works with: whole numbers, decimals, text, True and False, and None
  • How to check what kind of value you have, and how to turn one kind into another
  • The words Python keeps for itself, and the rules for naming your own things
  • Why the spaces at the start of a line change what your program does

Before going further, here is a variable in action. It is only four lines long.

A label and the value behind it

student = "Asha"
marks = 78

print(student)
print(marks)

You stored two pieces of information and read them back by name. That is the whole idea of a variable: write the name, get the value.

A variable is a name that holds a value, so you can use the value again later.

Introduction to Variables

What Is a Variable?

A variable is a name that holds a value.

You choose the name. Python keeps the value. Whenever you write the name again, Python gives you the value back. The name works like the label on a pocket: you read the label, and the pocket's contents come with it.

The name stands for the value

section = "7B"

print("Class:", section)
print("Class:", section)

You wrote section twice and got the same value twice. Nothing was used up. Reading a variable does not remove or change the value — you can read it as many times as you like.

Why Variables Are Used

Without variables you would have to repeat the same value everywhere.

Look at what that costs you:

The same value typed three times

print("Asha scored 78 marks")
print("Asha needs 22 more for full marks")
print("Asha is in class 7B")

Now suppose the student is really called Meera. You have to change three lines, and if you miss one, the program quietly lies.

With variables, the value lives in one place:

Change it once, and everything follows

student = "Meera"
marks = 78

print(student, "scored", marks, "marks")
print(student, "needs", 100 - marks, "more for full marks")
print(student, "is in class 7B")

Change the first line and all three lines change with it. That is the real reason variables exist: one value, one place. When the information changes — a different student, a corrected mark — you fix the program in one spot instead of hunting through it.

Creating Variables

You create a variable by writing a name, an equals sign, and a value.

name = value

Python does not need you to say what kind of value it is. It looks at the value and works that out. One line is enough — there is no separate step to announce the variable first.

Three variables, three kinds of value

student = "Asha"
marks = 78
average = 72.5

print(student, marks, average)

Variable Assignment

Storing a value in a name is called assignment. The = sign is the assignment operator.

= does not mean "is equal to" here. It means "put the value on the right into the name on the left". It always works right to left.

Right side first, then the name

marks = 70 + 8

print(marks)

Python worked out 70 + 8 first and got 78. Then it put 78 into marks.

The order matters. Python finishes everything on the right of the = before touching the name on the left. This will feel backwards at first if you have seen = in maths, but the right-to-left rule holds everywhere in Python.

Reassigning Variables

A variable can be given a new value at any time. The old value is gone.

The newest value is the one you get

marks = 78
print("First test:", marks)

marks = 85
print("Second test:", marks)

The name stayed the same. The value behind it changed. Nothing in Python stops you from overwriting, and there is no warning — the second assignment simply replaces the first.

A variable can even hold a different kind of value than before:

The kind of value can change too

answer = 42
print(answer, type(answer))

answer = "forty-two"
print(answer, type(answer))

First answer held a whole number. Then it held text. Python allowed both, because it decides the kind from the value, not from the name. Storing a different kind of value into the same name is usually a sign of confusing code, so it is best avoided — but Python does allow it.

Printing Variables

You print a variable by using its name inside print(), with no quote marks.

With quotes and without

student = "Asha"

print("student")
print(student)

The first line printed the word student, because quote marks mean "this is text, exactly as written". The second printed Asha, because a bare name means "look up the value".

This is one of the most common beginner mix-ups, and the output tells you immediately which one you wrote. If you see the variable name in the output instead of its value, look for quote marks around the name and remove them.

Deleting Variables

del removes a variable. After that, the name does not exist.

Using a name after deleting it

student = "Asha"
print(student)

del student
print(student)

Python stopped with NameError, because student no longer exists.

You will rarely need del. It is worth seeing once, because it shows that a name exists only from the moment you give it a value — nothing existed before that line, and nothing exists after del.

Multiple Assignment

Assigning Multiple Values

You can give several variables values in one line. Separate the names with commas, and the values with commas.

Three names, three values, one line

student, marks, section = "Asha", 78, "7B"

print(student, marks, section)

The first name takes the first value, the second takes the second, and so on. The counts must match — three names ask for exactly three values, no more and no fewer.

Assigning the Same Value to Multiple Variables

Chained = signs give the same value to several names.

One value, three names

maths = science = english = 0

print(maths, science, english)

All three start at zero. This is handy when you are about to count something up — three counters, all starting from the same clean slate, created in one line instead of three.

Unpacking Multiple Values

Taking the values out of a list or a tuple and putting them into names is called unpacking.

Pulling three values out of one list

marks = [78, 85, 60]
maths, science, english = marks

print("Maths:", maths)
print("Science:", science)
print("English:", english)

The number of names must match the number of values. If it does not, Python stops and says so:

Too few names for the values

marks = [78, 85, 60]
maths, science = marks

print(maths, science)

ValueError: too many values to unpack is Python telling you it had three values and only two places to put them. The message names the problem plainly, which is typical of Python errors — read it, count your names, count your values, and make the two agree.

Constants

What Are Constants?

A constant is a value that is not meant to change while the program runs.

The pass mark for a school year does not change halfway through. Neither does the number of days in a week. Values like these come from outside the program — from a school rule, a government rate, a calendar — and the program should simply use them, never alter them.

Constant Naming Conventions

Python has no special word for a constant. Instead, programmers agree on a signal: write the name in capital letters.

Capitals say: do not change this

PASS_MARK = 35
MAX_MARKS = 100

marks = 78

print("Pass mark:", PASS_MARK)
print("Percentage:", marks / MAX_MARKS * 100)

Capital letters are a message to other people reading the code. They are not a rule Python enforces. Anyone reading PASS_MARK = 35 knows at a glance that this value came from somewhere fixed and should be left alone.

Using Constants in Python

Python will let you change a constant. Nothing stops you:

Python allows it, people do not

PASS_MARK = 35
PASS_MARK = 50

print(PASS_MARK)

The value changed to 50 and Python said nothing. The capital letters only tell a human "this was not supposed to move". The protection is social, not technical — so when you see capitals in someone's code, including your own from last month, treat the value as fixed.

Use capitals for a value that is fixed by a rule outside your program: a pass mark, a tax rate, a maximum. Use small letters for anything the program works out as it goes.

Introduction to Data Types

What Are Data Types?

A data type is the kind of a value.

78 is a whole number. 72.5 is a decimal number. "Asha" is text. True is a yes-or-no answer.

The type decides what you can do with the value. You can divide two numbers. You cannot divide two names. Every type also has its own built-in actions, which you will see as the lesson goes on.

Dynamic Typing in Python

Python is dynamically typed. You never write the type down. Python reads the value and works it out.

Python names the type for you

student = "Asha"
marks = 78
average = 72.5
passed = True
remark = None

print(type(student))
print(type(marks))
print(type(average))
print(type(passed))
print(type(remark))

Five values, five types, and you declared none of them. Each name simply took the type of whatever you stored in it.

In some other languages you must write the type yourself, like int marks = 78;. Python works it out from the value instead, which means one less thing to write and one less thing to get wrong.

Why Data Types Matter

The type changes what an operation means. + is the clearest example.

One symbol, two different jobs

print(20 + 5)
print("20" + "5")

With numbers, + adds and gives 25. With text, + joins and gives 205.

Nothing is broken in the second line. Python did exactly what + means for text. This is why knowing the type matters, and it is the same trap you met with input() in the last lesson. When a result looks wrong, checking the types of the values involved is a good first move.

Numeric Types

Python has three types for numbers. You will use the first two constantly; the third you can safely ignore until you need it.

int

An int is a whole number. No decimal point. It can be negative, and it can be as large as your computer's memory allows.

Whole numbers, large and small

marks = 78
below_zero = -12
very_large = 2 ** 100

print(marks, below_zero)
print(very_large)
print(type(marks))

That last number is 2 multiplied by itself 100 times. Many languages cannot hold it in a whole number. Python can. You never have to worry about a whole number being "too big" — Python simply uses more memory as the number grows.

float

A float is a number with a decimal point.

Numbers with a decimal point

average = 72.5
temperature = -3.8

print(average + temperature)
print(type(average))

One thing to know early: a float is stored as an approximation, so some sums look slightly wrong.

A famous surprise

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))

0.1 + 0.2 gives 0.30000000000000004. That is not a Python bug. It is how computers store decimals, and every language that uses floats has the same result. Use round() when you are showing a number to a person. When money is involved, this tiny difference matters, so rounding before display is a habit worth forming now.

complex

A complex number has a real part and an imaginary part, written with a j.

A type you will rarely need

point = 3 + 4j

print(point)
print(point.real)
print(point.imag)
print(type(point))

Complex numbers are used in engineering and physics. You can safely forget about them until you need them, but it is worth knowing Python has them built in, so that 3 + 4j on a stranger's screen does not puzzle you later.

TypeWhat it holdsExample
inta whole number78, -12, 0
floata number with a decimal point72.5, -3.8
complexa real and an imaginary part3 + 4j

Boolean Type

bool

A bool holds one of two values: True or False. It is the answer to a yes-or-no question.

Both words start with a capital letter. true in small letters is not valid Python, and the editor will mark it in red the moment you type it.

A yes-or-no answer

marks = 78
passed = marks >= 35

print(passed)
print(type(passed))

marks >= 35 is a question: are the marks 35 or more? Python answered True. The answer is itself a value, so it can be stored in a variable and used later — exactly what happened here with passed.

Boolean Values (True and False)

Every value in Python can also be read as True or False when a yes-or-no answer is needed.

The empty ones count as False. Everything else counts as True.

What counts as False

print(bool(0))
print(bool(""))
print(bool([]))
print(bool(None))

print(bool(78))
print(bool("Asha"))

Zero, empty text, an empty list and None are all False. Any real value is True.

The logic is simple: anything with something in it counts as yes, and anything empty counts as no. This is why you can write if marks: to mean "if marks is not zero". It is short, and it is used everywhere in real Python.

Sequence Types

str

A str is text. The name is short for string, because it is a string of characters joined together.

You write text inside single or double quote marks. Both work the same way, so choose one and stay consistent within a program.

Text, and a few things text can do

student = "Asha"
remark = 'Good work'

print(student.upper())
print(len(student))
print(student + " - " + remark)
print(student[0])

len() counts the characters. student[0] gives the first character, because Python counts positions from 0, not 1. So student[1] is the second letter, not the first — remember this when a letter seems to be missing.

Text can be joined with + and repeated with *:

Joining and repeating text

line = "-" * 20

print(line)
print("Report card")
print(line)

"-" * 20 makes one piece of text containing twenty dashes. Joining and repeating like this is common when you want to lay out output neatly.

Strings do much more than this, and they get a lesson of their own later.

None Type

None

None means "no value yet".

It is not zero, and it is not empty text. A maths mark of 0 is a real mark; a missing mark is None. Python uses it to say that nothing has been decided or stored.

A value that means 'nothing yet'

remark = None

print(remark)
print(remark is None)

Use is None to test for it, not == None. Both work, but is None is the form every Python programmer writes, and consistency with other people's code is worth more than either choice on its own.

NoneType

None is the only value of its type, and that type is called NoneType.

One value, one type

remark = None

print(type(remark))

You will meet None often. A function that does not return anything gives you None, and a variable set up before its real value arrives is usually set to None first — for example, a remark field that stays empty until the teacher writes something.

Type Checking

Getting the Type with type()

type() tells you the type of a value. It is the tool you reach for whenever you are not sure what kind of value you are holding.

Asking what something is

print(type(78))
print(type(72.5))
print(type("Asha"))
print(type(True))

Four different values, four different answers, each printed clearly. You met type() briefly in the last lesson; here it becomes a working habit rather than a curiosity.

Checking Data Types

type() is good for looking. For a real test in your code, use isinstance(), which answers True or False.

Testing the type

marks = 78

print(isinstance(marks, int))
print(isinstance(marks, str))

isinstance(marks, int) asks "is this a whole number?" and gets True. The difference between the two tools is what they hand back: type() gives you a name to read, isinstance() gives you a yes-or-no your program can act on.

type() is for looking at a value while you learn. isinstance() is for a test your program makes a decision on.

Type Conversion

Type Conversion

Type conversion means turning a value of one type into another.

Python does some of this for you. The rest you ask for. The two kinds have names — implicit and explicit — and the next two sections show each in turn.

Implicit Type Conversion

Implicit conversion is the kind Python does on its own, without being asked.

Python widens the number for you

whole = 7
decimal = 2.5

total = whole + decimal

print(total)
print(type(total))

You added an int to a float and got a float. Python converted 7 to 7.0 first, because that keeps the answer exact.

Python only does this when nothing can be lost. It will never convert text to a number on its own:

Python will not guess

print("20" + 5)

TypeError is Python refusing to guess whether you meant 25 or 205. You have to say. The rule underneath this behaviour is worth remembering: Python converts between number types freely, but never touches text without an explicit instruction.

Explicit Type Conversion (Casting)

Explicit conversion is when you ask for it by name. It is also called casting.

Saying which one you meant

text = "20"
number = 5

print(int(text) + number)
print(text + str(number))

The first line turns the text into a number and adds: 25. The second turns the number into text and joins: 205. Same two values, two different answers, and you chose. That choice — not luck — is what explicit conversion gives you.

Type Conversion Functions

Four functions cover almost everything you will need. Each takes a value of another type and produces the type in its name.

int()

int() makes a whole number. From text, from a decimal, or from True and False.

Making a whole number

print(int("78"))
print(int(72.9))
print(int(True))

Notice that int(72.9) gives 72, not 73. It cuts the decimal part off; it does not round. Use round() when you want the nearest whole number.

int() fails if the text is not a number:

Text that is not a number

print(int("seventy-eight"))

ValueError: invalid literal for int() means the text could not be read as a number. The text must contain digits — int("78") works, int("seventy-eight") does not.

float()

float() makes a decimal number.

Making a decimal number

print(float("72.5"))
print(float(78))
print(float("3"))

float(78) gives 78.0. The value has not changed, only its type — it is now written with a decimal point, and it behaves as a float from that point on.

str()

str() makes text out of anything.

Making text

marks = 78

print(str(marks) + " marks")
print(str(72.5))
print(str(True))

str() never fails. Every value can be shown as text. This makes it the safe way to join a number into a sentence with +, because + refuses to join a number to text directly.

bool()

bool() answers "does this count as True?"

Making a yes-or-no value

print(bool(78))
print(bool(0))
print(bool("False"))

Look at the last line. bool("False") is True, because it is text with characters in it, and any text that is not empty counts as True. Python read it as a string, not as the word False. When converting text to a real yes-or-no, you have to compare it yourself, for example with text == "yes".

int(72.9) gives 72, not 73. And bool("False") is True. Both surprise people, and both follow the plain rule: cut the decimal off, and any non-empty text counts as True.

FunctionTurns a value intoExampleResult
int()a whole numberint("78")78
float()a decimal numberfloat("72.5")72.5
str()textstr(78)"78"
bool()True or Falsebool(0)False

Python Reserved Words

Introduction to Keywords

A keyword is a word Python keeps for itself. It is part of the language, so you cannot use it as a name.

A keyword cannot be a name

class = "7B"
print(class)

SyntaxError appears because class already means something to Python: it starts a class definition. Use section or class_name instead. The error may look odd the first time — Python complains about the one word, not the whole line — but the fix is always the same: pick a different name.

List of Python Keywords

Python can list its own keywords.

Every keyword Python has

import keyword

print(len(keyword.kwlist))
print(keyword.kwlist)

There are 35 of them. You do not have to memorise the list. You will learn most of them as you use them, and the editor marks a misuse straight away.

GroupKeywords
Yes-or-no valuesTrue, False, None
Making decisionsif, elif, else
Repeatingfor, while, break, continue
Building blocksdef, return, class, lambda
Comparing and testingand, or, not, in, is
Handling problemstry, except, finally, raise, assert
Everything elseimport, from, as, with, pass, del, global, nonlocal, yield, await, async

Using Python Keywords Correctly

The safe habit is simple. If a word turns a different colour in the editor the moment you type it, it is a keyword, so pick another name.

A safe name instead of a keyword

section = "7B"
is_pass = True

print(section, is_pass)

section instead of class. is_pass instead of pass. Both read just as well — and a by-product of avoiding keywords is that your names become more specific, which is good for the reader anyway.

Python Identifiers

Introduction to Identifiers

An identifier is a name you give something: a variable, a function, a class.

student, marks and PASS_MARK are all identifiers. The word sounds formal, but it just means "a name you made up". Python has rules about which names it accepts, and they are next.

Identifier Naming Rules

Python has four rules, and they are all strict.

  1. Use letters, digits and the underscore _ only.
  2. Do not start with a digit.
  3. No spaces.
  4. Do not use a keyword.

Capital and small letters are different. marks, Marks and MARKS are three separate names.

Case matters

marks = 78
Marks = 85

print(marks)
print(Marks)

Two names that look almost the same hold two different values. This is a real source of bugs, so pick one spelling and keep to it. Accidentally typing Marks on one line and marks on the next can give you either a wrong value or a NameError, and the mistake is hard to see on the screen.

Valid and Invalid Identifiers

A name that starts with a digit

1st_student = "Asha"
print(1st_student)

SyntaxError, because the name begins with a digit. first_student works.

NameAllowed?Why
student_nameyesletters and an underscore
marks2yesa digit is fine, just not first
_totalyesan underscore may start a name
2marksnostarts with a digit
student namenocontains a space
student-nameno- means subtraction
classnoa Python keyword

Naming Conventions

Rules say what Python allows. Conventions say what other programmers expect.

  • Variables and functions: small letters with underscores — student_name, pass_mark
  • Constants: capitals with underscores — PASS_MARK
  • Classes: each word capitalised, no underscores — StudentRecord

This style is called snake_case for the small-letter names, because the underscores look like a snake lying between the words.

Most of all, use a name that says what the value is. marks tells the reader something. m does not. A descriptive name costs a few extra keystrokes once and saves everyone — including you, weeks later — real guessing time.

A name that explains itself

total_marks = 450
subject_count = 6

print("Average:", total_marks / subject_count)

Nobody has to ask what that program does. The names carry the meaning, which is the mark of well-chosen identifiers.

Lines and Indentation

Introduction to Indentation

Indentation is the blank space at the start of a line.

In most languages it is decoration. In Python it is part of the language. The spaces decide which lines belong together — so indenting wrongly does not make the code look untidy, it makes the program do something different or refuse to run.

Code Blocks in Python

A group of lines that belong together is a block. A line ending in : starts one, and the indented lines under it are the block.

The indented lines belong to the if

marks = 78

if marks >= 35:
    print("Passed")
    print("Well done")

print("Report printed")

The two indented lines run only when the test is true. The last line is not indented, so it belongs to no block and always runs.

Other languages use curly brackets for this. Python uses the spaces you can already see, and that has a practical benefit beyond looks: you cannot indent a line one way and bracket it another. What the code shows is what the code means.

Indentation Rules

  • Use four spaces for each level. This is what the whole Python world does.
  • Every line in the same block needs the same indentation.
  • Never mix tabs and spaces in one file.

Two levels of indentation

marks = 78

if marks >= 35:
    print("Passed")
    if marks >= 75:
        print("Distinction")

print("Done")

Distinction is two levels in, so it runs only when both tests are true. Each extra level of indentation means "only if the line above was true".

Common Indentation Errors

Forgetting to indent after a : stops the program:

Nothing indented after the colon

marks = 78

if marks >= 35:
print("Passed")

IndentationError: expected an indented block means Python opened a block and found nothing in it. The : promised indented lines, so Python will not run the program until they appear.

Indenting a line that should not be indented is the same kind of error:

An indent that belongs to nothing

marks = 78
    print(marks)

IndentationError: unexpected indent, because nothing above it opened a block. The fix is to remove the extra spaces so the line lines up with its neighbours.

Set your editor to insert four spaces when you press Tab. It is one setting, and it removes a whole class of errors before you ever meet them.

Common mistakes

Each row is one mistake. The middle column is what you will actually see on screen. Every beginner meets several of these, so if a strange message appears, find the row, apply the fix, and carry on.

MistakeWhat you seeWhy it happensFix
Printing a name inside quote marksstudent instead of AshaQuote marks mean "this exact text", so the name is never looked upDrop the quotes: print(student)
Using a name before giving it a valueNameError: name 'total' is not definedA name exists only from the line that assigns itAssign it above the line that uses it
Two spellings of one nameA value that never changes, or a NameErrormarks and Marks are two different namesPick one spelling and keep to it
Adding text to a numberTypeError: can only concatenate str+ cannot join a number to textstr(marks) or int(text), whichever you meant
Expecting int() to roundint(72.9) gives 72int() cuts the decimal offUse round(72.9) for 73
Trusting a decimal to be exact0.1 + 0.2 shows 0.30000000000000004Floats are stored as approximations in every languageUse round() when showing it to a person
Unpacking the wrong number of valuesValueError: too many values to unpackThe names on the left must match the values on the rightCount both sides
Using a keyword as a nameSyntaxError: invalid syntaxWords like class and pass belong to PythonRename to section, is_pass
Starting a name with a digitSyntaxError: invalid syntaxA name may contain digits but not begin with onefirst_student, not 1st_student
Forgetting to indent after a colonIndentationError: expected an indented blockA : promises a block, and the block has to be thereIndent the next line by four spaces
Mixing tabs and spacesTabError: inconsistent use of tabs and spacesPython counts the spaces, and a tab is not a fixed number of themSet the editor to four spaces

What to Remember

  • A variable is a name that holds a value, so you can use the value again later.
  • = means "put the value on the right into the name on the left". It is not a question.
  • A variable can be given a new value, and even a new kind of value, at any time.
  • a, b = 1, 2 assigns in one line, and the two sides must match in number.
  • A constant is written in CAPITALS. Python does not enforce it; other people read it.
  • The main types are int, float, complex, bool, str and NoneType.
  • The type decides what an operation means. 20 + 5 is 25; "20" + "5" is 205.
  • type() is for looking. isinstance() is for testing.
  • Python converts between number types on its own, but never between text and numbers. For that, use int(), float(), str() or bool().
  • Keywords belong to Python. Your own names use letters, digits and underscores, and never start with a digit.
  • Indentation is part of the language. Four spaces per level, and never mix tabs with spaces.

Next: Operators