Python Variables
- What they are
- The dynamic nature of Python's typing
- The rules for naming them
- Advanced concepts like variable references and memory management.
A variable is a reserved memory location used to store a value. In Python, you can think of a variable as a name or label that you attach to a piece of data. When you create a variable, you are telling the computer, "Remember this piece of information, and let me refer to it later by this name."
Unlike some other programming languages (like C++ or Java), Python is dynamically typed. This means you do not need to declare the type of the variable before assigning a value. The interpreter infers the type based on the data you assign.
The Analogy: Labels, Not Boxes
A common misconception among beginners is to think of variables as "boxes" that hold data. A more accurate analogy in Python is to think of them as name tags.
You create the data (like an integer
5or a string"Hello").You attach a name tag to it (like
xormessage).If you want to change the value, you simply move the name tag to a new piece of data.
Syntax:
- Creating a variable in Python is incredibly simple. You use the equals sign (
=), known as the assignment operator. Syntax:
variable_name = value
Rules for Naming Variables (Identifiers)
Hard Rules (Must Follow)
Start with a Letter or Underscore: A variable name must begin with a letter (a-z, A-Z) or an underscore (
_). It cannot start with a number.
- Invalid:
1variable
- Valid:
my_var,_private,variable1
@, #, $, %) are allowed.- Invalid:
user-name,$amount,first name
- Valid:
user_name,data2
3. Case-Sensitive: Python treats uppercase and lowercase letters differently.
age,Age, andAGEare three completely different variables.
4. No Keywords: You cannot use reserved words (keywords) that Python uses for its own syntax (like loops, conditionals, etc.).
Invalid:
if,else,while,for,class,import,True,False
Conventions (Good Practice)
Snake Case: By convention, Python uses snake_case for variable names. This means words are separated by underscores, and all letters are lowercase.
- first_name = "John"
- total_price = 100
Descriptive Names: Avoid single-letter names (except in simple loops). Use names that describe the data.
- Bad:
d = "2023-10-05"
- Good:
expiration_date = "2023-10-05"
Memory Management: How Variables Really Work
Objects and References
Python creates an integer object containing the value
500and stores it in memory.The variable
abecomes a reference (a pointer) to that memory location.When we assign
b = 500, Python creates a new integer object (unless it's a small integer, due to interning) and hasbreference it.
The id() Function
- You can see the memory address (or a unique identifier) of an object using the
id()function.
Global Variables
- Variables defined outside of any function (at the top level of a script) are global. They can be accessed from anywhere in the code, but modifying them inside a function requires the
globalkeyword.
Comments
Post a Comment