Python 3 — Variables & Core Data Types
Think of a variable as a storage box with a label stuck to it. You write a label on the box (the variable name), put something inside it (the value), and then look it up whenever you need it. Python handles variables dynamically, meaning you don't have to state what type of data goes in the box beforehand.
To store a value in a variable, we use the assignment operator (=). The variable name goes on the left, and the value goes on the right:
# Storing data in variables
username = "Balaji"
age = 25
height = 5.9
is_developer = True
# Printing the variables
print(username)
print(age)
print(height)
print(is_developer)
Every piece of data stored in Python belongs to a specific category. Here are the 4 fundamental types you must know:
| Type | Class Name | Description | Example |
|---|---|---|---|
| Text | str (String) | Unicode characters wrapped in quotes | "Python 3" |
| Whole Number | int (Integer) | Positive or negative whole values | -42 |
| Decimal | float (Float) | Numbers with decimal points | 3.1415 |
| Boolean | bool (Boolean) | Logical state representing true/false | True or False |
You can check the type of any variable using the built-in type() function:
score = 99
print(type(score)) # Outputs: <class 'int'>
is_online = False
print(type(is_online)) # Outputs: <class 'bool'>
In languages like Java or C++, once you declare a variable as an integer, you can never store a string inside it. Python is **dynamically typed**, meaning variables can change their type easily as you assign new values:
data = 100
print(type(data)) # <class 'int'>
data = "Now I am text!"
print(type(data)) # <class 'str'>
- Variable names can only contain letters, numbers, and underscores (e.g.,
user_1). - They must **never** start with a number (e.g.,
1useris invalid). - Use standard **snake_case** (all lowercase words connected by underscores) to follow clean Python guidelines (PEP 8).
- Do not use reserved keywords like
if,else,class, orprintas variable names.
Write a program that declares a variable representing a product price, discount rate, product name, and whether it is in stock. Output their values and their types to the terminal.