Python Variables
In Python, variables are used to store data values. Python has a flexible and dynamic way of handling variables, meaning you don’t need to explicitly declare the type of a variable before using it. The type of the variable is inferred based on the value assigned to it.
1. Variable Assignment
You can assign a value to a variable using the equals sign =.
x = 5 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
2. Dynamic Typing
Python is dynamically typed, meaning you don’t need to specify the type of a variable. You can also reassign variables to different types on the fly.
x = 10 # x is an integer
x = "Hello" # Now x is a string
3. Multiple Assignments
You can assign multiple variables in a single line, which can be useful for clean and concise code.
a, b, c = 1, 2, 3 # Assigns a = 1, b = 2, c = 3
You can also assign the same value to multiple variables in one line.
x = y = z = 100 # x, y, and z are all assigned the value 100
4. Variable Naming Rules
- Variable names must start with a letter (a-z, A-Z) or an underscore (
_), but they cannot start with a number. - Variable names can only contain letters, numbers, and underscores.
- Variable names are case-sensitive (
nameandNameare different variables). - Avoid using Python keywords as variable names (e.g.,
if,while,for).
my_variable = 10 # Valid
myVariable = 20 # Valid (common in some styles)
123var = 30 # Invalid (can't start with a number)
5. Best Practices for Variable Names
- Use descriptive variable names to make your code more readable.
x = 10 # Not clear what x represents age = 10 # Clearer and more descriptive - In Python, the most common naming convention is snake_case, where words are separated by underscores (
_).user_name = "Alice" # Snake case (most common in Python) userName = "Bob" # Camel case (used in some other languages)
6. Types of Variables
Python variables can hold various data types, such as:
- Numbers (
int,float,complex):x = 10 # int y = 3.14 # float z = 1 + 2j # complex - Strings:
name = "Alice" - Lists (ordered, mutable):
fruits = ["apple", "banana", "cherry"] - Tuples (ordered, immutable):
point = (1, 2) - Dictionaries (key-value pairs):
person = {"name": "Alice", "age": 25} - Booleans (
TrueorFalse):is_valid = True - None (represents the absence of a value):
result = None
7. Changing Variable Types
You can change the type of a variable by reassigning it a value of a different type.
x = 10 # x is an integer
x = "Ten" # Now x is a string
8. Type Casting
You can manually convert a variable from one type to another using Python’s built-in type casting functions.
x = 5 # Integer
y = float(x) # Converts x to float
z = str(x) # Converts x to string
# Output: x is an integer, y is a float, z is a string
print(type(x), type(y), type(z))
int(): Converts to integer.float(): Converts to float.str(): Converts to string.bool(): Converts to boolean.
9. Global and Local Variables
- Local variables are declared inside a function and can only be used within that function.
- Global variables are declared outside of functions and can be accessed by any function in the program.
x = "global"
def my_function():
x = "local"
print(x) # Output: local
my_function()
print(x) # Output: global
To modify a global variable inside a function, use the global keyword.
x = "global"
def change_global():
global x
x = "modified"
change_global()
print(x) # Output: modified
10. Constants
Python does not have a built-in constant type, but you can indicate that a variable should not change by using all-uppercase letters. This is a convention, not a rule.
PI = 3.14159 # Treat PI as a constant
Example of Python Variable Usage:
# Variable assignment
age = 25
name = "Alice"
is_student = True
# Using variables
print(f"My name is {name}, I am {age} years old, and student status: {is_student}")
# Variable type change
age = "Twenty-five"
print(f"My age is now represented as: {age}")
# Using lists
fruits = ["apple", "banana", "cherry"]
print(f"I like to eat {fruits[0]}")
# Using dictionaries
person = {"name": "Alice", "age": 25}
print(f"{person['name']} is {person['age']} years old")