Introduction to Variables
Variables are a fundamental concept in any programming language. They act as storage containers for data values. In Python, variables are dynamically typed, meaning that you do not need to declare the type of a variable when you create one. The type is inferred from the value you assign to it.
Defining Variables
In Python, you define a variable by assigning a value to a name using the =
operator. For example:
Here, x
is an integer variable, name
is a string variable, and is_active
is a boolean variable.
Rules for Variable Names
When naming variables in Python, you must follow these rules:
- Variable names must start with a letter (a-z, A-Z) or an underscore (_).
- The remaining characters can be letters, numbers, or underscores.
- Variable names are case-sensitive (
age
andAge
are different variables). - You cannot use reserved keywords as variable names (e.g.,
class
,for
,if
, etc.).
Here are some examples of valid and invalid variable names:
Variable Types and Dynamic Typing
Python supports various data types, including:
- Integers: Whole numbers (e.g., 1, -3, 42)
- Floats: Decimal numbers (e.g., 3.14, -0.001, 2.0)
- Strings: Sequences of characters (e.g., “hello”, ‘world’)
- Booleans: True or False values
- Lists: Ordered sequences of items (e.g., [1, 2, 3], [“a”, “b”, “c”])
- Tuples: Immutable ordered sequences of items (e.g., (1, 2, 3), (“x”, “y”, “z”))
- Dictionaries: Key-value pairs (e.g., {“name”: “Alice”, “age”: 25})
- Sets: Unordered collections of unique items (e.g., {1, 2, 3}, {“a”, “b”, “c”})
Python’s dynamic typing means you can change the type of a variable simply by assigning a value of a different type:
Basic Operations with Variables
Arithmetic Operations
You can perform arithmetic operations with numeric variables:
String Operations
You can concatenate and repeat strings:
Boolean Operations
You can use logical operators with boolean variables:
Variable Scope
The scope of a variable determines where it can be accessed. Python has three types of variable scopes:
- Local Scope: Variables defined within a function are local to that function.
- Global Scope: Variables defined outside of all functions are global.
- Enclosing Scope: Variables defined in the outer function for nested functions.
Local Variables
Local variables are accessible only within the function where they are defined:
Global Variables
Global variables are accessible throughout the entire script:
Enclosing Variables
Variables defined in the enclosing function are accessible to nested functions:
Modifying Global Variables
To modify a global variable inside a function, you must use the global
keyword:
Variable Lifespan
The lifespan of a variable is determined by its scope. Local variables exist only as long as the function is executing, while global variables exist for the duration of the program.
Advanced Variable Concepts
Mutable and Immutable Types
In Python, data types can be mutable or immutable:
- Immutable Types: Integers, floats, strings, and tuples. Once created, their values cannot be changed.
- Mutable Types: Lists, dictionaries, and sets. You can modify their contents.
Here are examples illustrating mutable and immutable types:
Variable Aliasing
Aliasing occurs when two variables refer to the same object:
To avoid aliasing, you can create a copy of the object:
Best Practices for Using Variables
- Use Descriptive Names: Choose variable names that describe their purpose (e.g.,
total_price
,user_age
). - Follow Naming Conventions: Use snake_case for variables (e.g.,
my_variable
) and PascalCase for class names (e.g.,MyClass
). - Keep Scope Minimal: Define variables in the smallest scope necessary to improve code readability and maintainability.
- Avoid Global Variables: Minimize the use of global variables to prevent unintended side effects and make the code easier to debug.
- Use Constants for Fixed Values: Define constants (unchanging values) using uppercase names (e.g.,
PI = 3.14
).
Practical Example for Best Practice
Let’s create a simple calculator that performs basic arithmetic operations: