What is a Variable?
A variable is a name that acts as a reference or a container to store data in memory. Variables allow programmers to store, manipulate, and retrieve data during the execution of a program.
For example:
name = "Alice"
age = 25
Here, name
and age
are variables storing the values "Alice"
and 25
, respectively.
Rules for Naming Variables
- Variable names must start with a letter (a–z, A–Z) or an underscore (
_
).- Correct:
name
,_age
- Incorrect:
2name
(cannot start with a number)
- Correct:
- Variable names can only contain letters, numbers, and underscores (
_
).- Correct:
user_age
,number123
- Incorrect:
user-age
(hyphens are not allowed)
- Correct:
- Variable names are case-sensitive.
Age
andage
are two different variables.
- Reserved keywords (like
if
,else
,while
, etc.) cannot be used as variable names.
How to Declare a Variable
Variables in Python are dynamically typed, which means you don’t need to declare the type of the variable explicitly. Python automatically determines the type based on the assigned value.
Example:
x = 10 # Integer
name = "John" # String
price = 19.99 # Float
is_active = True # Boolean
Updating Variable Values
Variables can be updated by simply assigning them a new value:
x = 5 # x initially holds 5
x = x + 10 # x now holds 15
Types of Variables
- Integer: Holds whole numbers.
count = 10
- Float: Holds decimal numbers.
price = 9.99
- String: Holds a sequence of characters.
greeting = "Hello, World!"
- Boolean: Holds either
True
orFalse
.is_valid = True
Multiple Assignments
Python allows assigning values to multiple variables in a single line:
a, b, c = 1, 2, 3
Or assigning the same value to multiple variables:
x = y = z = 0
Checking Variable Type
You can check the type of a variable using the type()
function:
x = 10
print(type(x)) # Output: <class 'int'>
y = "Hello"
print(type(y)) # Output: <class 'str'>
Deleting Variables
You can delete a variable using the del
keyword:
x = 10
del x
print(x) # This will raise a NameError since x no longer exists.
Best Practices
- Use meaningful variable names that clearly describe the data they hold.
age = 25 # Good a = 25 # Avoid single letters
- Use snake_case for variable names.
user_name = "Alice" # Preferred userName = "Alice" # Less common in Python
Example Code
Here’s a sample code to tie everything together:
# Declare variables
name = "Alice"
age = 30
height = 5.6
is_student = True
# Print variable values
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is a student:", is_student)
# Update a variable
age = age + 1
print("Updated Age:", age)
# Check variable types
print(type(name)) # Output: <class 'str'>
print(type(age)) # Output: <class 'int'>
print(type(height)) # Output: <class 'float'>
print(type(is_student)) # Output: <class 'bool'>