Index
What is a Variable?
A variable is a name that refers to a value stored in memory. In Python, you don’t need to declare the type of a variable explicitly—Python determines it automatically.
1. Declaring a Variable
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_valid = True # Boolean
Here,
x
stores an integer (int
).y
stores a floating-point number (float
).name
stores a string (str
).is_valid
stores a boolean (bool
).
2. Variable Naming Rules
When naming variables, follow these rules: ✅ Allowed:
- Must start with a letter (a-z, A-Z) or an underscore
_
- Can contain letters, digits (0-9), and underscores
- Case-sensitive (
name
andName
are different)
❌ Not Allowed:
- Cannot start with a digit (
1name
❌) - Cannot contain special characters (
name@
❌) - Cannot use reserved keywords like
class
,def
,if
, etc.
✔ Valid Examples:
my_var = 10
_name = "Python"
user_age = 25
❌ Invalid Examples:
1name = "Alice" # ❌ Starts with a number
user@name = "Bob" # ❌ Contains @
class = "Math" # ❌ Uses a reserved keyword
3. Dynamic Typing
Python allows reassignment of variables with different types.
x = 5 # Integer
x = "Hello" # Now x is a string
print(x) # Output: Hello
4. Assigning Multiple Variables
You can assign multiple variables in one line.
a, b, c = 1, 2, 3
print(a, b, c) # Output: 1 2 3
Or assign the same value to multiple variables.
x = y = z = 10
print(x, y, z) # Output: 10 10 10
5. Type Checking and Type Conversion
To check a variable’s type, use type()
.
x = 5
print(type(x)) # Output: <class 'int'>
You can also convert data types:
x = "100"
y = int(x) # Converts string to integer
print(y, type(y)) # Output: 100 <class 'int'>
6. Global and Local Variables
- Local variables are declared inside a function and used only there.
- Global variables are declared outside functions and can be accessed anywhere.
global_var = "I am global"
def my_function():
local_var = "I am local"
print(local_var) # Accessible inside function
my_function()
print(global_var) # Accessible anywhere
To modify a global variable inside a function, use the global
keyword:
x = 10
def update():
global x
x = 20
update()
print(x) # Output: 20
7. Constants in Python
Python does not have built-in constants, but by convention, constants are written in uppercase.
PI = 3.14159
GRAVITY = 9.8
Even though Python allows changing them, it’s a best practice not to modify constants.
8. Deleting Variables
You can delete a variable using del
.
x = 100
del x
print(x) # ❌ Error: x is not defined