Python · Basics

Complete Guide to Python Data Types & Variables

Everything in Python is an object, and every object has a data type. Variables are names that point to these objects in memory. In Python, data types classify the kind of values (like numbers, text, or collections), while variables are named references that store those values. Python is dynamically typed, meaning you don’t declare types explicitly—types are inferred when you assign a value

1. What Is a Variable?

A variable is a named reference to a value in memory. You create a variable by assigning it a value. In Python, a variable is a name that refers to a value stored in memory. It acts like a container that holds data, and you create it simply by assigning a value with the operator.

In Python, you do not need to declare the type of a variable. Python figures it out automatically.

2. Variable Naming Rules

Variable names must follow these rules:

Valid variable names

Invalid variable names

2name = "Alex"   # ❌ starts with number
class = "Math"   # ❌ 'class' is a keyword

3. Python Built-In Data Types (Overview)

Core data types you will use all the time:

TypeNameExample
intInteger5, -10, 100
floatFloating point3.14, 0.5, -9.8
strString"Hello", 'Python'
boolBooleanTrue, False
listList[1, 2, 3]
tupleTuple(1, 2)
setSet{1, 2, 3}
dictDictionary{"a": 1}
NoneTypeNoneNone

4. Integers (int)

An integer () in Python is a whole number, positive or negative, without a fractional or decimal part.Integers are whole numbers (no decimal part). Integers in Python are whole numbers ( type). • They can be positive, negative, or zero. • Python supports multiple number bases and unlimited integer size. • You can perform arithmetic and comparison operations directly on them.

x = 10
y = -5
z = 0

Common operations

a = 5 + 3    # 8
b = 10 - 4   # 6
c = 6 * 2    # 12
d = 10 // 3  # 3  (integer division)
e = 10 % 3   # 1  (remainder)
f = 2 ** 3   # 8  (power)

5. Floats (float)

Floats represent numbers with a decimal point. A float in Python is a number with a decimal point or written in exponential (scientific) notation. It represents real numbers (numbers that can have fractional parts). The type is float . Floats represent real numbers with decimals or scientific notation. Stored in double precision with ~15–17 digits accuracy. Support arithmetic, comparisons, and conversions. Useful for calculations involving fractions, measurements, or continuous values.

pi = 3.14
temperature = -5.5
score = 100.0

Float precision:

x = 0.1 + 0.2
print(x)  # 0.30000000000000004

This is normal floating-point behavior in most programming languages.

6. Strings (str)

Strings are used for text data. A string in Python is a sequence of characters (letters, numbers, symbols, spaces) enclosed in quotes. Strings are used to represent textual data. The type is str. Immutable: Once created, strings cannot be changed. Any modification creates a new string. Indexing & slicing: Strings are sequences, so you can access parts of them

name = "Python"
message = 'Hello World'

Multi-line strings

text = """This
is
multi-line text"""
print(text)

Basic string operations

name = "Python"

print(name.upper())  # "PYTHON"
print(name.lower())  # "python"
print(len(name))     # 6
print(name[0])       # "P"
print(name[-1])      # "n"

7. Booleans (bool)

Booleans represent truth values: True or False. Logical values: Used to represent conditions, states, or flags. Derived from integers: Internally,True is equivalent to 1 and False is equivalent to 0.
You can convert other types to Boolean using bool():

Numbers:0 → False, non-zero → True

Strings: Empty string "" → False, non-empty → True

Collections: Empty (, , ) → False, non-empty → True

is_active = True
password_correct = False

Often used in conditions:

if password_correct:
    print("Access granted")
else:
    print("Access denied")

8. Lists (list)

Lists store multiple items in an ordered, mutable collection. A list in Python is an ordered, mutable collection of items. It can hold elements of different data types (integers, strings, floats, even other lists). The type is list().
Ordered: Items maintain the order in which they are added.

Mutable: You can change, add, or remove elements after creation.

Indexing & slicing: Access elements by position.
Useful List Methods
→ Sorts the list in place.

→ Reverses the list.

→ Adds elements from another list.

→ Creates a shallow copy.

→ Removes all elements.

colors = ["red", "green", "blue"]
numbers = [1, 2, 3, 4, 5]

Access and modify:

print(colors[0])   # "red"
colors[1] = "yellow"
colors.append("purple")
print(colors)

9. Tuples (tuple)

Tuples are like lists, but immutable (cannot be changed). A tuple in Python is an ordered, immutable collection of items. Like lists, tuples can store elements of different data types (numbers, strings, other tuples, etc.). The type is tuple().
Ordered: Elements maintain the order in which they are defined.

Immutable: Once created, you cannot change, add, or remove elements.

Indexing & slicing: Works the same way as lists.

position = (10, 20)
point = (3, 4)

Access values:

print(position[0])  # 10

Trying to change a value causes an error:

# position[0] = 99  # ❌ TypeError

10. Sets (set)

Sets store unique, unordered values. A set in Python is an unordered collection of unique elements. Sets are useful when you want to store items without duplicates and perform mathematical set operations (union, intersection, difference). The type is set()
Useful Methods:

- len(s) → number of elements

- clear() → remove all elements

- copy() → shallow copy

- update() → add multiple elements

- issubset() / issuperset() → check relationships between sets

numbers = {1, 2, 3, 2}
print(numbers)  # {1, 2, 3}

They are useful for removing duplicates and doing set operations.

11. Dictionaries (dict)

Dictionaries store data as key : value pairs. A dictionary in Python is an unordered, mutable collection of key–value pairs. It’s used to store data that can be quickly retrieved using a unique key instead of an index. The type is dict().
Keys and values:

Keys must be immutable (e.g., strings, numbers, tuples).

Values can be of any type (including lists, other dictionaries, etc.).

Unordered: Items don’t have a fixed position (though since Python 3.7, insertion order is preserved).

Mutable: You can add, update, or remove key–value pairs.

Fast lookup: Accessing values by key is very efficient.

user = {
    "name": "Alex",
    "age": 25
}

print(user["name"])  # "Alex"

12. None Type (NoneType)

None represents the absence of a value. - None() in Python is a special constant that represents the absence of a value or a null value. - The type of None is NoneType. - It’s often used to indicate that a variable, function, or object doesn’t hold meaningful data.
- Singleton: There is only one instance of None in a Python program.

- Truth value: In Boolean contexts, None is treated as False.

- Falsy value: In Boolean contexts, None is treated as False.

x = None

if x is None:
    print("x has no value yet")

Often used for default values or to indicate "no result".

13. Checking Data Types with type()

You can use type() to see the data type of a variable. is a built-in Python function used to check the data type of a variable or value. It returns the class type of the object. You can pass any object (variable, literal, or expression) into type():
- isinstance() vs type():

- type() checks the exact type.

- isinstance() checks if an object is an instance of a class or its subclasses (more flexible)

x = 10
y = "Hello"
z = 3.14

print(type(x))  # <class 'int'>
print(type(y))  # <class 'str'>
print(type(z))  # <class 'float'>

14. Dynamic Typing in Python

Python is dynamically typed, which means that a variable can change its type during program execution. Dynamic typing in Python means that variables don’t have fixed types. Instead, the type is determined at runtime based on the value assigned. This allows the same variable to hold different types of data during program execution. In statically typed languages (like Java, C++), you must declare a variable’s type before using it. In Python (dynamically typed), you simply assign a value, and Python infers the type automatically. The type can change later if you assign a new value of a different type.

x = 10        # x is an int
x = "Hello"   # now x is a str
print(x)

This is powerful, but you must be careful to avoid type-related bugs. Key Characteristics
Type inference: Python figures out the type at runtime.

Flexibility: Variables can change type freely.

No declarations: You don’t need to specify types when creating variables.

Runtime binding: The type is bound to the value, not the variable name.
✅ Advantages
Ease of use: Faster coding, especially for beginners and rapid prototyping.

Flexibility: A single variable can adapt to different types.

Conciseness: Less boilerplate code compared to statically typed languages.
⚠️ Disadvantages
Runtime errors: Type mismatches aren’t caught until execution.

Harder debugging: Bugs may appear if variables change type unexpectedly.

Performance: Type checking at runtime can be slower than static typing.

15. Type Conversion (Casting)

You can manually convert between data types using casting functions. Type conversion (casting) means changing a value from one data type to another.
Python supports two kinds of type conversion:

1. Implicit conversion (Type Casting by Python itself)

2. Explicit conversion (Manual Casting by the programmer)

Implicit Type Conversion

Python automatically converts smaller data types into larger ones to avoid data loss.

Example: converting to during arithmetic.

int("10")      # 10
float("3.5")   # 3.5
str(100)       # "100"
bool(1)        # True
bool(0)        # False


Explicit Type Conversion

You manually convert data types using built-in functions.

Common casting functions:

→ converts to integer

→ converts to float

→ converts to string

→ converts to list

→ converts to tuple

→ converts to set

Example with user input:

age = int(input("Enter your age: "))
print("Next year you will be", age + 1)

16. Multiple Assignment

Python lets you assign multiple variables in one line. Multiple assignment means assigning values to multiple variables at once in a single line. Python allows this for convenience and cleaner code.

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

Assign the same value to multiple variables:

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

17. Variable Scope (Local vs Global)

Scope refers to the region of a program where a variable is accessible. In Python, variables can be local (inside a function) or global (outside all functions). Local variables are defined inside functions and only exist there. Global variables are defined outside functions and can be accessed inside them (with some rules).

Local variable example


Declared inside a function.

Accessible only within that function.

Created when the function is called, destroyed when the function ends.

def my_func():
    x = 10   # local variable
    print(x)

my_func()
# print(x)  # ❌ Error: x is not defined outside

Global variable example


Declared outside any function.

Accessible from anywhere in the code, including inside functions.

Exists for the lifetime of the program.

x = 5   # global variable

def show():
    print(x)

show()  # 5

18. Constants (By Convention)

Python does not have true constants, but by convention, variables written in UPPERCASE are treated as constants and should not be changed.

PI = 3.14159
GRAVITY = 9.8

19. Mutable vs Immutable Types

Some data types can be changed (mutable), while others cannot (immutable).

TypeMutable?
int❌ Immutable
float❌ Immutable
str❌ Immutable
tuple❌ Immutable
list✅ Mutable
dict✅ Mutable
set✅ Mutable

Immutable objects cannot be changed in place; operations create new objects. Mutable objects can be modified without changing their identity.

20. Real-World Example

This small program combines variables, input, data types, and conversion.
Enter your name and age:

21. Summary

In this guide, you learned:

Data types and variables are the foundation of all Python programs. Understanding them clearly will make everything else in Python much easier.