Variables and Data Types
Variables are the foundation of all programming. They allow us to store, modify, and reuse data efficiently. In Python, variables are incredibly flexible thanks to the language’s **dynamic typing** — you can assign any type of data to a variable without explicitly declaring its type.
Chapter 1: Introduction to Python Programming
Sub-chapter: Variables and Data Types
Variables are the foundation of all programming. They allow us to store, modify, and reuse data efficiently. In Python, variables are incredibly flexible thanks to the language’s dynamic typing — you can assign any type of data to a variable without explicitly declaring its type.
🧠 What Is a Variable?
A variable is a named storage location that holds a value in memory. You can think of it like a label stuck on a box — you can change what’s inside the box at any time, and Python keeps track of what type of data it contains automatically.
name = "Alice"
age = 25
height = 1.68
is_student = True
Each variable points to a specific value in memory. Python’s interpreter automatically determines the type of each variable at runtime.
✍️ Variable Naming Rules
To ensure readable and error-free code, Python enforces simple naming rules:
- Must start with a letter (A–Z, a–z) or an underscore (
_). - Can contain letters, digits, and underscores, but no spaces or special symbols.
- Are case-sensitive —
age,Age, andAGEare three distinct variables. - Cannot use Python keywords (like
if,for,class,True, etc.).
✅ Good examples:
user_name = "Rambod"
max_score = 100
pi_value = 3.14159
🚫 Bad examples:
2user = "Alice" # Starts with a number ❌
user-name = "Bob" # Hyphens are not allowed ❌
class = "Python" # 'class' is a reserved keyword ❌
💡 Tip: Follow the snake_case naming style — it’s the Python convention used by professionals.
⚙️ Variable Assignment and Reassignment
Assign a value using the = operator. You can also change the value later — Python will automatically update the variable’s type if needed.
x = 10
print(x) # 10
x = "Ten"
print(x) # Ten (type changed from int → str)
You can even assign multiple variables in one line:
name, age, country = "Alice", 25, "Iran"
print(name, age, country)
Or assign the same value to multiple variables:
x = y = z = 0
🧩 Python Data Types Overview
Python is dynamically typed, so you don’t have to declare a variable’s type — it’s inferred from the assigned value. Here are Python’s core built‑in types:
| Category | Type | Description | Example |
|---|---|---|---|
| Numeric | int | Whole numbers | 42, -7 |
| Numeric | float | Decimal (floating‑point) numbers | 3.14, -0.5 |
| Text | str | Sequence of characters | "Hello" |
| Sequence | list | Ordered, changeable collection | [1, 2, 3] |
| Sequence | tuple | Ordered, immutable collection | (4, 5, 6) |
| Set | set | Unordered, unique items | {1, 2, 2, 3} → {1, 2, 3} |
| Mapping | dict | Key‑value pairs | {"name": "Alice", "age": 25} |
| Boolean | bool | Logical values | True, False |
| None | NoneType | Represents “no value” | None |
🔢 Numeric Types
# Integer
score = 95
# Float
temperature = 36.6
# Operations
result = score / 2
print(result) # 47.5
You can mix integers and floats in arithmetic expressions — Python automatically promotes types when needed.
🧵 Strings (str)
Strings store textual data. They can be enclosed in single quotes (’ ’), double quotes (” ”), or even triple quotes (''' ''' or ) for multi-line text.
greeting = "Hello, Python!"
multiline = '''This is
a multi-line
string.'''
print(greeting)
print(multiline)
String concatenation and formatting:
name = "Rambod"
print("Hello, " + name + "!")
print(f"Welcome, {name}.") # f-string formatting
🧮 Lists (list)
A list is an ordered, mutable collection. You can add, remove, or modify its items.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
fruits.append("orange") # add
fruits.remove("banana") # remove
print(fruits)
🪶 Tuples (tuple)
Tuples are like lists but immutable — once created, their elements cannot be changed.
coordinates = (10, 20)
print(coordinates[0]) # 10
They are often used to store fixed sets of data, like geographic coordinates or RGB color values.
🧰 Sets (set)
Sets are unordered collections that automatically remove duplicates.
numbers = {1, 2, 3, 3, 4}
print(numbers) # {1, 2, 3, 4}
You can perform mathematical set operations:
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union → {1, 2, 3, 4, 5}
print(a & b) # Intersection → {3}
🗺️ Dictionaries (dict)
Dictionaries store key-value pairs, making it easy to access data using meaningful keys.
person = {
"name": "Alice",
"age": 25,
"is_student": True
}
print(person["name"]) # Alice
person["age"] = 26 # update value
Dictionaries are extremely powerful — they form the backbone of JSON, APIs, and data structures used in web and AI applications.
🧩 Booleans (bool)
Booleans represent True or False values, used in conditions and control flow.
is_logged_in = True
is_admin = False
print(is_logged_in and not is_admin) # True
They’re often the result of comparisons:
x = 10
y = 20
print(x < y) # True
🔄 Type Conversion (Casting)
You can manually convert values from one type to another:
x = 3.14
y = int(x) # 3
z = str(y) # "3"
w = float("2.5") # 2.5
Be careful converting strings to numbers — invalid conversions like
int("abc")will raise an error.
🧾 Checking Data Type
Use the built-in type() function to inspect a variable’s type.
a = "hello"
b = 10
print(type(a)) # <class 'str'>
print(type(b)) # <class 'int'>
🧮 Practical Example: Combining Types
name = "Alice"
age = 25
height = 1.72
is_student = True
print(f"{name} is {age} years old, {height}m tall, student: {is_student}")
Output:
Alice is 25 years old, 1.72m tall, student: True
🧱 Key Takeaways
- Variables store data that can change over time.
- Python infers data types automatically.
- Use descriptive, readable names for variables.
- Learn how to convert between types safely.
- Mastering variables and data types gives you the foundation to handle any kind of information in Python.
Now that you understand variables and data types, you have the essential tools to begin writing logic and performing operations in Python confidently.