Variables in Python
A variable is a name that refers to a value stored in the computer’s memory. In Python, variables are used to store data that can be used and manipulated later in the program.
Key Points About Variables in Python
-
No explicit declaration needed:
You don’t need to declare a variable type beforehand. Just assign a value, and Python figures out the type automatically.
-
Dynamic typing:
The type of a variable can change during execution.
-
Case sensitive:
myVar
and myvar
are different variables.
-
Naming rules:
- Variable names must start with a letter (a-z, A-Z) or underscore
_
.
- The rest can be letters, digits (0-9), or underscores.
- Cannot use Python reserved keywords like
if
, for
, while
, etc.
Assigning Variables
Assign a value using the =
operator:
x = 10 # Integer
name = "Alice" # String
pi = 3.14 # Float
is_valid = True # Boolean
Variables Can Change Type
var = 5 # Initially an integer
print(var) # Output: 5
var = "Hello" # Now a string
print(var) # Output: Hello
Multiple Assignments
You can assign values to multiple variables in one line:
a, b, c = 1, 2, 3
print(a, b, c) # Output: 1 2 3
Assign the same value to multiple variables:
x = y = z = 0
print(x, y, z) # Output: 0 0 0
Using Variables
You can use variables in expressions:
a = 10
b = 20
c = a + b
print(c) # Output: 30
Variable Types (Examples)
age = 25 # int
price = 19.99 # float
first_name = "John" # str
is_student = False # bool
Variable Naming Best Practices
- Use descriptive names, e.g.,
total_price
, user_age
.
- Use lowercase with underscores for readability (
snake_case
).
- Avoid single letters except for counters or indices (
i
, j
).
Example Program Using Variables
# Store user information
name = "Alice"
age = 30
height = 5.5 # in feet
print(f"{name} is {age} years old and {height} feet tall.")
Output:
Alice is 30 years old and 5.5 feet tall.