6. Variables and Data Types in Python
Variables and data types are the foundation of programming in Python. Every program you write will store, modify, and process data. Understanding how Python handles variables and different types of data is essential before moving to advanced topics.
1) What Is a Variable?
A variable is a name that refers to a value.
In Python, you create a variable using the assignment operator =.
name = "Ali"
age = 25
price = 19.99
Python automatically detects the data type based on the assigned value.
2) Variable Naming Rules
- Must start with a letter or underscore
- Cannot start with a number
- Cannot use reserved keywords (like if, for, class)
- Use snake_case for readability
user_name = "Sara"
total_amount = 100
is_active = True
3) Basic Data Types in Python
A) String (str)
Strings represent text and are enclosed in quotes.
message = "Hello Python"
print(type(message))
B) Integer (int)
Integers are whole numbers.
age = 30
print(type(age))
C) Float (float)
Floats are numbers with decimal points.
price = 49.99
print(type(price))
D) Boolean (bool)
Boolean values represent True or False.
is_logged_in = True
print(type(is_logged_in))
4) Complex Data Types
A) List
Lists store multiple values in order.
fruits = ["apple", "banana", "orange"]
print(fruits[0])
B) Tuple
Tuples are similar to lists but cannot be modified.
coordinates = (10, 20)
print(coordinates)
C) Dictionary
Dictionaries store key-value pairs.
user = {"name": "Omar", "age": 22}
print(user["name"])
D) Set
Sets store unique values.
numbers = {1, 2, 3, 3}
print(numbers)
5) Type Conversion (Casting)
Sometimes you need to convert between types.
age = "25"
age_number = int(age)
price = 10
price_text = str(price)
input() always returns a string.
Use int() or float() when needed.
6) Checking Data Types
value = 100
print(type(value))
The type() function helps you debug and understand what kind of data you are working with.
7) Best Practices
- Use meaningful variable names
- Avoid overwriting built-in names (like list, str, int)
- Keep consistent naming style
- Understand the type before performing operations
Conclusion
Variables allow you to store data, and data types define how that data behaves. By mastering strings, numbers, booleans, lists, dictionaries, and type conversion, you build the core foundation of Python programming.
Practice by creating small examples and experimenting with different data types. The more you manipulate data, the more comfortable you become.