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 (
1totalis invalid,total1is fine). - Names are case sensitive:
total,TotalandTOTALare three different variables. - By convention, Python variable names use snake_case — lowercase words separated by underscores, like
first_nameortotal_price. - Reserved keywords such as
class,fororifcannot 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:
| Type | Description | Example |
|---|---|---|
int | Whole numbers, positive or negative | 42, -7 |
float | Numbers with a decimal point | 3.14, -0.5 |
str | Text, wrapped in quotes | "hello" |
bool | Truth value, only two possible values | True, False |
NoneType | Represents the absence of a value | None |
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