Chapter 1

Variables and Data Types

Learn how Python stores values in variables and the core built-in data types.

A variable is a name that points to a value in memory. In Python you create a variable simply by assigning to it with the equals sign. You do not declare a type first — Python figures out the type from the value you give it.

Creating variables

name = 'Aisyah'
age = 17
height = 1.62
is_student = True

Here name holds text, age holds a whole number, height holds a decimal number, and is_student holds a truth value.

Core built-in types

  • int — whole numbers, such as 0, 42, -5.
  • float — numbers with a decimal point, such as 3.14 or -0.5.
  • str — text (a string), written in single or double quotes.
  • bool — either True or False (note the capital letters).

Checking the type

Use the built-in type() function to see what type a value is:

print(type(age))     # <class 'int'>
print(type(height))  # <class 'float'>
print(type(name))    # <class 'str'>

Naming rules

  • Names may use letters, digits and the underscore, but cannot start with a digit.
  • Names are case sensitive: age and Age are different.
  • By convention use lowercase words joined by underscores, such as first_name.
  • Avoid reserved words like if, for or class.

Reassigning and converting

A variable can point to a new value at any time, even of a different type:

x = 10
x = 'ten'   # now x is a string

You can convert between types with int(), float() and str():

price = int('25')      # the string '25' becomes the number 25
label = str(25)        # the number 25 becomes the string '25'

Be careful: int('hello') fails because that text is not a number. Convert only text that really looks like a number.

Assigning several variables at once

Python lets you set more than one variable on a single line, which is handy for related values:

x, y, z = 1, 2, 3
print(x)   # 1
print(z)   # 3

You can also give the same value to several names together:

a = b = 0
print(a, b)   # 0 0

The None value

Python has a special value called None that means no value yet. It is often used as a starting placeholder:

result = None

Comments

Anything after a hash symbol on a line is a comment. Python ignores it, so use comments to explain your code to human readers:

total = 100   # this is a comment

Remember

  • Assignment reads right to left: the value on the right is stored in the name on the left.
  • True and False start with a capital letter in Python.
  • Use type() when you are unsure what a variable currently holds.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor