Data Types & Variables
Understanding variables and data types is fundamental to writing any program in Python. These are the basic building blocks that help store, classify, and manipulate information.
What is a Variable?
A variable is a named location in memory used to store data. You can think of it like a labeled box that holds something. You can change what’s inside the box anytime.
Example:
In Python, you don’t need to declare a data type explicitly — Python figures it out based on the value.
Common Python Data Types
Python has several built-in data types. Let’s explore the most commonly used ones:
Integer (int
) – Whole numbers (positive or negative)
→ Example: x = 10
Float (float
) – Numbers with decimals
→ Example: price = 99.99
String (str
) – A sequence of characters/text
→ Example: title = "Python Basics"
Boolean (bool
) – True or False values
→ Example: is_active = True
List – Ordered collection of items
→ Example: colors = ["red", "green", "blue"]
Dictionary (dict
) – Key-value pairs
→ Example: student = {"name": "Raj", "age": 20}
Dynamic Typing in Python
Python is dynamically typed, meaning:
- You don’t need to declare variable types.
- You can assign a value of one type, then later assign a value of another type to the same variable.
But while Python allows it, it’s usually better practice to keep variable types consistent to avoid confusion.
Type Checking and Conversion
You can check a variable’s type using the type()
function:
You can also convert between data types:
Summary
- A variable holds data.
- Python supports different data types like int, float, str, bool, list, and dict.
- Python is dynamically typed, meaning you don’t have to declare types.
- Use
type()
to check a variable’s type and functions likeint()
,str()
, orfloat()
to convert.