Variables & Data Types

A variable is simply a name that refers to a value stored in memory. Python makes creating variables very easy: there is no type keyword to write, no separate declaration step, and no semicolon to remember.

Declaring a Variable

You create a variable simply by assigning a value to a name with =. Python figures out the type automatically from the value on the right.

x = 5
name = "Sonu"
price = 19.99
is_active = True

print(x, name, price, is_active)

Dynamic Typing

Python is dynamically typed, which means a variable is not locked to the type of its first value. The same variable name can be reassigned to a value of a completely different type later in the program.

x = 5          # x is currently an int
print(type(x))

x = "hello"    # now x is a str, and that's perfectly legal
print(type(x))

Naming Rules and Conventions

  • A name can contain letters, digits and underscores, but it cannot start with a digit (1total is invalid, total1 is fine).
  • Names are case sensitive: total, Total and TOTAL are three different variables.
  • By convention, Python variable names use snake_case — lowercase words separated by underscores, like first_name or total_price.
  • Reserved keywords such as class, for or if cannot be used as variable names.

Core Built-in Data Types

Every value in Python has a type. The most common built-in types you will use constantly are:

TypeDescriptionExample
intWhole numbers, positive or negative42, -7
floatNumbers with a decimal point3.14, -0.5
strText, wrapped in quotes"hello"
boolTruth value, only two possible valuesTrue, False
NoneTypeRepresents the absence of a valueNone

Checking a Variable's Type

The built-in type() function tells you exactly what kind of value a variable currently holds, which is especially useful given Python's dynamic typing.

x = 10
y = 3.5
z = "text"
flag = False
empty = None

print(type(x))      # <class 'int'>
print(type(y))      # <class 'float'>
print(type(z))      # <class 'str'>
print(type(flag))   # <class 'bool'>
print(type(empty))  # <class 'NoneType'>

Type Conversion (Casting)

You can explicitly convert a value from one type to another using the int(), float() and str() built-in functions.

age_text = "25"
age_number = int(age_text)     # "25" -> 25

count = 5
count_text = str(count)        # 5 -> "5"

pi_text = "3.14"
pi_number = float(pi_text)     # "3.14" -> 3.14

print(age_number + 1)   # 26

Note: Trying to convert text that is not a valid number, such as int("hello"), raises a ValueError.

Multiple Assignment in One Line

Python lets you assign several variables at once by separating both the names and the values with commas.

a, b, c = 1, 2, 3
print(a, b, c)  # 1 2 3

# the same value can also be assigned to multiple names at once
x = y = z = 0
print(x, y, z)  # 0 0 0
Next steps: Head to Operators to learn how to combine and compare these values.