Variables and Data Types
Learn how to store information in variables and understand the different types of data Python works with.
A variable is a labeled box
Programs need to remember things, like a user's name or score. A variable is a named storage location. Think of a box. You write a name on the outside, put something inside, and use the label whenever you need what is in the box.
Creating one is simple. Write the name, an equals sign, then the value:
name = "Alice"
age = 25
height = 1.65
is_student = True
The equals sign does not ask a question here. It is an assignment, meaning put this value into this variable. Always read it from right to left: the value on the right goes into the name on the left.
Python also decides the kind of value for you. You never have to say "this is a number". It looks at the value and works it out, which is part of why Python is easy to start with.
Using and changing variables
Once a variable exists, use it anywhere by writing its name:
name = "Alice"
print(name)
print("Hello, " + name)
Alice
Hello, Alice
Notice there are no quotes around name in print(name). With quotes, Python would print the word name. Without quotes, it looks inside the box. You can change the value at any time:
score = 0
print(score)
score = 10
print(score)
0
10
You will also see lines that start with # in the examples. Those are comments, notes for humans that Python ignores. The next lesson covers them fully.
A variable only remembers its latest value. The old value is gone once you store a new one. You can also copy one variable into another, and use a variable to build a new value from itself:
a = 5
b = a # b now holds 5 too
a = 8 # changing a does not touch b
print(a, b) # 8 5
lives = 3
lives = lives - 1
print(lives) # 2
That last example reads as: take the current value of lives, subtract 1, and put the result back into lives. You will see this pattern everywhere.
Naming rules
Break these and Python gives you an error:
- Letters, numbers and underscores only, like
my_nameorscore1 - Never start with a number:
1scoreis invalid,score1is fine - No spaces. Use an underscore:
first_name, notfirst name - Names are case sensitive.
name,NameandNAMEare three different variables - Names cannot be Python keywords like
if,fororwhile. Also avoid built-in names likeprint,typeorlist, because reusing them breaks those tools
These rules are what Python demands. There is also a style that every Python programmer follows: write names in lowercase with underscores between words, like total_price. This is called snake_case.
# Good names tell you what is inside
user_age = 30
total_price = 19.99
# Poor names make you guess
x = 30
tp = 19.99
Pick names that explain themselves. Code is read far more often than it is written, and a clear name saves you from writing a comment. Avoid names that are very long, too, since number_of_students_in_the_class becomes tiring fast.
The four basic types
Every value in Python has a type. The type tells Python what kind of data it is and what you can do with it. You can add two numbers, but adding a number to a person's name makes no sense. The four basic types are:
- int: whole numbers with no decimal point, like
5,-3or100 - float: numbers with a decimal point, like
3.14,-0.5or100.0 - str: text inside quotes like
"hello"or"123". Notice"123"is a string, not a number, because of the quotes - bool: only
TrueorFalse, with a capital first letter
The word float is short for floating point. Even 100.0 is a float because of the decimal point, while 100 is an int.
Single or double quotes both make a string, so 'hi' and "hi" are the same. The difference between 5 and "5" is huge, though. The first is a number you can do math with. The second is just a character that looks like a number.
print(5 + 5) # 10, math on numbers
print("5" + "5") # 55, text glued together
Booleans are the answers to yes or no questions. You will use them a lot when your programs start making decisions. Capital letters matter, since true in lowercase is an error.
Check it, convert it
The type() function tells you what a value is:
x = 42
print(type(x)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hi")) # <class 'str'>
print(type(True)) # <class 'bool'>
To change a value from one type to another, use int(), float() or str(). This is called type conversion:
age_text = "25"
age_number = int(age_text)
print(age_number + 1) # 26
print(int(9.99)) # 9, the decimal is cut off
print(str(42)) # "42" as text
Notice that int(9.99) gives 9, not 10. It cuts the decimal part off and does not round. Also be aware that not everything can be converted. int("hello") fails with an error because "hello" is not a number.
Several variables at once
Python lets you save lines by creating several variables in one go:
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
a = b = 0 # both start at 0
print(a, b) # 0 0
You can also swap two values without a helper box, which is something many other languages cannot do so neatly:
first = "left"
second = "right"
first, second = second, first
print(first, second) # right left
A value that never changes while your program runs is called a constant. Python has no special keyword for it, but programmers write the name in capital letters as a signal to everyone: "do not change this".
PI = 3.14159
MAX_PLAYERS = 4
Python will not stop you from changing a constant. The capital letters are just a promise between programmers.
Common mistakes
- Using a name before creating it.
print(score)beforescore = 0gives aNameError, because Python has never heard ofscore. - Mixing up quotes and names.
print("name")shows the word name.print(name)shows what is stored in the variable. - Adding text and numbers.
"Age: " + 25fails. Convert withstr(25)or use an f-string (you will learn them in the strings lesson). - Wrong capitals.
Trueworks,truedoes not.Nameandnameare different variables. - Using
=when you mean==. One equals assigns. Two equals compares. More on this in the if statements lesson.
print(score) # NameError: name 'score' is not defined
score = 0
When you see a NameError, check your spelling and make sure the variable was created on an earlier line.
Key takeaways
- A variable is a named box.
name = valueputs a value into it - Names use letters, numbers and underscores, never start with a number, and are case sensitive
- Use clear snake_case names such as
total_price - The four basic types are int, float, str and bool
type()checks a type.int(),float()andstr()convert between types- Anything in quotes is text, even if it looks like a number