Skip to content

Variables and types

~15 min ยท prerequisite: Showing output and reading input

What you will be able to do

  • Create a variable, give it a value, and change that value later.
  • Name variables so they follow Python's rules.
  • Use type to find out which kind of value a variable holds, and convert between int, float, and str.

The idea

A variable is a name that refers to a value. You create one with an assignment, which is written with a single equals sign. The line score = 10 does not ask whether score equals 10. It tells Python to store 10 under the name score. Think of a labeled box: the label is the name, and the box holds the value. You can put a different value in the same box later, and the label stays the same.

Names must follow a few rules. A name may contain letters, digits, and underscores. It may not start with a digit, so 1st is not allowed, but first_1 is. It may not be one of Python's reserved keywords, such as class or if. Names are case-sensitive, which means Total, total, and TOTAL are three different names. A common style is lowercase words joined by underscores, such as total_price.

Every value has a type, which tells Python what kind of value it is and what operations make sense for it. These are the four types you will meet first:

  • An integer, written int, is a whole number such as 7 or -3.
  • A float is a number with a decimal point, such as 2.5.
  • A string, written str, is text in quotes, such as "Ada". The quotes are not part of the text.
  • A boolean, written bool, has one of two values, True or False.

The function type tells you the type of any value. Python decides the type from the value you assign, so you do not declare it in advance. A variable can even change type if you assign a new value of a different type, although doing that often makes code harder to read.

Types also limit what you can do. You can add two integers, but adding an integer and a string is not allowed. You can convert between types with int, float, and str. Conversion creates a new value of the requested type. For example, int("42") gives the integer 42, and str(42) gives the text "42".

Two values can look the same on screen and still be different. The text "2" and the integer 2 are not equal. Keep this in mind, because it causes many of the errors in this course.

Worked example

city = "Lagos"
population = 1000
area = 2.5
is_capital = False

print(type(city))
print(type(population))
print(type(area))
print(type(is_capital))

Line by line, this is what Python does:

  1. city = "Lagos" stores the string "Lagos" under the name city. The quotes mark the value as text.
  2. population = 1000 stores the integer 1000.
  3. area = 2.5 stores the float 2.5, because the value has a decimal point.
  4. is_capital = False stores the boolean False. Note the capital letter, which Python requires.
  5. Each print(type(...)) line asks for the type of one variable and shows it. The output is <class 'str'>, <class 'int'>, <class 'float'>, and <class 'bool'>. The word class is how Python displays a type.

Now the same idea with conversion.

count_text = "3"
count = int(count_text)
print(count + 1)

The conversion turns "3" into the integer 3, so the addition works and the output is 4.

Try it

The first block checks the type of each kind of value. The second block shows reassignment and conversion. The third block checks name rules that Python accepts.

age = 17
price = 2.5
name = "Ada"
is_student = True

assert type(age) is int
assert type(price) is float
assert type(name) is str
assert type(is_student) is bool
score = 10
score = score + 5
assert score == 15

text = str(score)
assert text == "15"
assert type(text) is str
assert int("42") + 1 == 43
assert float("2.5") * 2 == 5.0
total_2 = 3
Total = 1
total = 2
assert total_2 == 3
assert Total != total
assert Total == 1

Common mistakes

  1. Using = to compare. = stores a value. To check equality, use ==. Writing assert score = 15 gives a SyntaxError: invalid syntax message, and the check should be assert score == 15.

  2. Starting a name with a digit. Writing 1st = 5 gives:

    SyntaxError: invalid decimal literal
    

    Rename it to first or first_1.

  3. Using a keyword as a name. Writing class = 5 gives:

    SyntaxError: invalid syntax
    

    Choose a different name, such as grade_class.

  4. Expecting "2" to equal 2. The following check fails:

    x = "2"
    assert x == 2
    
    AssertionError
    

    The text "2" and the integer 2 are different types. Use int(x) to convert first.

  5. Using a variable before it exists. Writing print(total) before any line creates total gives:

    NameError: name 'total' is not defined
    

Practice

  1. Create a variable named city that holds your home town as a string. Use type to check it is a str.
  2. Create a variable temperature with the value 21.5. Add an assert that checks its type is float.
  3. Create count with the value 5. Then add 3 to it and assert the new value is 8.
  4. Convert the string "100" to an integer, add 1, and assert the result is 101.
  5. Stretch: create price_text = "7". Convert it to an integer, multiply it by 3, convert the result back to a string, and assert that the final value equals "21".
Solution
  1. python city = "Berlin" assert type(city) is str

Replace Berlin with your home town.

  1. python temperature = 21.5 assert type(temperature) is float

  2. python count = 5 count = count + 3 assert count == 8

  3. python number = int("100") assert number + 1 == 101

  4. python price_text = "7" price = int(price_text) total = price * 3 final = str(total) assert final == "21"

Recap

  • = stores a value under a name. == compares two values.
  • Names may contain letters, digits, and underscores, cannot start with a digit, and are case-sensitive.
  • Use type to see a value's type, and int, float, or str to convert between them.

Sources