✅ Python Variables – Full Guide
🔹 What is a Variable?
A variable is a container for storing data values. It acts as a label pointing to a memory location where the value is stored.
📌 Think of it like:
age = 25
Means “store 25 in a box labeled age.”
🔹 How to Create a Variable
name = "Arvind"
age = 25
price = 99.99
is_online = True
✅ Python detects the data type automatically — no need to declare type like in C++ or Java.
🔹 Variable Naming Rules
Rule | Example |
---|---|
Must start with a letter or _ |
✅ name , _score |
Can't start with a number | ❌ 1age |
No spaces | ❌ user name |
Case-sensitive | Name ≠ name |
Use descriptive names | ✅ user_age |
🔹 Data Types with Variables
# Integer
x = 10
# Float
pi = 3.14
# String
city = "Nashik"
# Boolean
logged_in = False
Use type()
to check data type:
print(type(city)) # <class 'str'>
🔹 Multiple Assignments
a, b, c = 1, 2, 3
x = y = z = 100
print(a, b, c)
print(x, y, z)
🔹 Dynamic Typing
Python is dynamically typed, so you can reassign different data types to the same variable.
x = 10 # int
x = "Ten" # now it's a string
🔹 Type Casting (Convert Data Type)
a = "123"
b = int(a) # converts string to integer
x = 5.5
y = str(x) # converts float to string
print(type(b), type(y))
🔹 Constants in Python (by convention)
Python doesn't have real constants, but we use uppercase to show it shouldn’t change.
PI = 3.14159
GRAVITY = 9.8
🔹 Memory Reference (Advanced Insight)
a = 5
b = a # both point to same memory
print(id(a), id(b)) # Same IDs
Reassigning b = 6
will change its memory location.
✅ Best Practices
✅ Use snake_case for variable names
✅ Make names meaningful
✅ Use constants for fixed values
✅ Don’t reuse variables unnecessarily
✅ Keep naming consistent
🔚 Summary
Concept | Example |
---|---|
Create Variable | x = 5 |
Data Types | int , float , str , bool |
Check Type | type(x) |
Reassign Variable | x = "hello" |
Multiple Assignment | a, b = 1, 2 |
0 Comments