Python Variables
1. What is a Variable?
- A variable is a named location in memory used to store data.
- It acts as a container for storing values that can be used and manipulated throughout a program.
2. Variable Naming Rules
- Valid Names:
- Must start with a letter (a-z, A-Z) or an underscore (
_). - Can contain letters, numbers (0-9), and underscores.
- Case-sensitive (
age,Age, andAGEare different variables).
- Must start with a letter (a-z, A-Z) or an underscore (
- Invalid Names:
- Cannot start with a number.
- Cannot contain spaces or special characters (e.g.,
@,#,$). - Cannot be a Python keyword (e.g.,
if,else,for,while).
3. Assigning Values to Variables
- Use the assignment operator
=to assign a value to a variable. - Python is dynamically typed, so you don’t need to declare the type of a variable explicitly.
4. Multiple Assignments
- You can assign multiple variables in a single line.
5. Variable Types
- Python variables can hold data of different types:
- Integer: Whole numbers (e.g.,
10,-5) - Float: Decimal numbers (e.g.,
3.14,-0.001) - String: Text (e.g.,
"Hello",'Python') - Boolean:
TrueorFalse - List: Ordered, mutable collection (e.g.,
[1, 2, 3]) - Tuple: Ordered, immutable collection (e.g.,
(1, 2, 3)) - Dictionary: Key-value pairs (e.g.,
{"name": "Alice", "age": 25}) - Set: Unordered, unique elements (e.g.,
{1, 2, 3})
- Integer: Whole numbers (e.g.,
6. Dynamic Typing
- Python is dynamically typed, meaning the type of a variable is determined at runtime and can change.
7. Type Checking
- Use the
type()function to check the type of a variable.
8. Variable Scope
- Local Scope: Variables defined inside a function are local to that function.
- Global Scope: Variables defined outside a function are global and can be accessed anywhere.
9. Deleting Variables
- Use the
delkeyword to delete a variable.
10. Constants
- Python doesn’t have built-in support for constants, but by convention, use uppercase names for constants.
11. Best Practices
- Use descriptive variable names (e.g.,
user_ageinstead ofua). - Follow naming conventions (e.g.,
snake_casefor variable names). - Avoid using single-letter variable names unless in loops or mathematical contexts.