Introduction to variables¶
- Variables are fundamental components in Python and many other programming languages. They are used to store data that can be manipulated and processed in your programs.
- A variable in Python is a named storage location that can hold data. It's like a container where you can store different types of information, such as numbers, text, lists, or more complex data structures.
- Variables are allow you to manipulate and work with data in your programs.
- The type of data a variable can hold is determined by Python based on the value you assign to it. This means you can use variables to store integers, decimals, characters, and more, without specifying a type.
- Variables are created automatically when you assign a value to them. Python doesn't require you to declare the type of a variable; it figures it out on its own based on the assigned value.
Variable Declaration and Assignment¶
- In Python, you don't need to declare the data type of a variable explicitly. You can create a variable and assign a value to it in a single step.
# Variable assignment
my_variable_1 = 42
print(my_variable_1)
42
Variable Types¶
Python has various variable types, including:
- int: Integer values (e.g., 42, -7).
- float: Floating-point values (e.g., 3.14, -0.5).
- str: Strings (e.g., "Hello, World!").
- bool: Boolean values (True or False).
- list: Ordered, mutable collections of values.
- tuple: Ordered, immutable collections of values.
- dict: Key-value mappings (dictionaries).
my_integer = 51
my_float = 3.14
my_string = "Intensity Coding"
my_bool = True
my_list = [1, 2, 3]
my_set = {1, 2, 3}
my_tuple = (4, 5, 6)
my_dict = {"name": "Raj", "age": 37}
Type Function : type() function give data type of variables¶
print(type(my_integer))
print(type(my_float))
print(type(my_string))
print(type(my_bool))
print(type(my_list))
print(type(my_set))
print(type(my_tuple))
print(type(my_dict))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'list'> <class 'set'> <class 'tuple'> <class 'dict'>
Casting : If you want to specify the data type of a variable, this can be done with casting.¶
x = str(5) # x will be '5'
y = int(5) # y will be 5
z = float(5) # z will be 5.0
Quotes in string : String variables can be declared either by using single or double quotes.¶
x = "intensity"
# is the same as
x = 'intensity'
Variable Naming Conventions¶
- A variable can have a short name (like x and y) or a more descriptive name (my_variable,num1).
Variable Naming Rules:
- A variable name must start with a letter or the underscore character.
- They cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (name and NAME are different variables)
- A variable name cannot be any of the Python keywords.
# Valid Name
myvariable = "intensity"
my_variable = "intensity"
_my_variable = "intensity"
myVariable = "intensity"
MYVARIABLE = "intensity"
myvariable2 = "intensity"
# Invalid Name which show Error
2myvariable = "intensity"
my-variable = "intensity"
my variable = "intensity"
File "<ipython-input-31-c79e2d4c8407>", line 2 2myvariable = "intensity" ^ SyntaxError: invalid decimal literal
# Variable names are case-sensitive
name = 4
NAME = "intensity"
#NAME will not overwrite name
Multi Words Variable Names
- Variable names with more than one word can be difficult to read so there are several techniques you can use to make them more readable.
# Camel Case : Each word, except the first, starts with a capital letter
myVariable = "intensity"
# Pascal Case : Each word starts with a capital letter
MyVariable = "intensity"
# Snake Case : Each word is separated by an underscore character
my_variable = "intensity"
Multiple Assignment¶
- One Value to Multiple Variables: You can assign the same value to multiple variables in one line
x = y = z = 1
- Many Values to Multiple Variables: You can assign multiple variables at once using unpacking. Make sure the number of variables matches the number of values, or else you will get an error.
x, y, z = 1, 2, 3
- Variable Packing and Unpacking : Python supports variable packing and unpacking, which allows you to assign multiple values to or from a single variable.
coordinates = (3, 4)
x, y = coordinates # Unpack the tuple into variables
Print the Variables¶
x = "How are you ?"
print(x)
How are you ?
# You can put multiple variables, separated by a comma in print()
x = 1
y = 2
z = 3
print(x, y, z)
1 2 3
# You can use + operator to print multiple variables in print()
x = "1 "
y = "2 "
z = "3 "
print(x + y + z)
1 2 3
# For numbers the + character works as a mathematical operator
x = 3
y = 1
print(x + y)
4
# If you combine a string and a number with the + operator, Python will give you an error
x = 5
y = "intensity"
print(x + y)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-ad057ec50799> in <cell line: 4>() 2 x = 5 3 y = "intensity" ----> 4 print(x + y) TypeError: unsupported operand type(s) for +: 'int' and 'str'
# The best way to print multiple variables in the print() function is to separate them with commas, which even support different data types
x = 5
y = "intensity"
print(x, y)
5 intensity
Deleting Variables¶
You can delete a variable using the del keyword.
You can delete a single object or multiple objects by using the del statement.
del var
del var_a, var_b
x = 10
del x
# Now x is undefined and trying to access it will raise an error.
Local and Global Variable¶
- Local variables are defined inside functions and are only accessible within that function's scope.
- Global variables are defined outside functions and can be accessed from anywhere in the code.
# This is a global variable
global_var = 10
def show_values():
local_var = 5 # Local variable defined inside function
print("Inside function:")
print("Global variable:", global_var)
print("Local variable:", local_var)
show_values()
# Accessing global variable outside function
print("Outside function:")
print("Global variable:", global_var)
# Trying to access local variable outside its scope will raise an error
# print(local_var) # Uncommenting this will raise: NameError
Inside function: Global variable: 10 Local variable: 5 Outside function: Global variable: 10
- If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
x = "Good"
def greet():
x = "Best" # Local x shadows global x
print("Inside function: Python is", x)
greet()
print("Outside function: Python is", x)
Inside function: Python is Best Outside function: Python is Good
Keyword global:¶
If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. The global keyword makes the variable global.
Also, use the global keyword if you want to make a change to a global variable inside a function.
Example 1: Creating a global variable from inside a function¶
def create_global():
global x
x = 142 # Declared as global, now exists outside the function
create_global()
print(x) # Output: 142
142
Example 2: Modifying a global variable inside a function¶
x = 142
def update_global():
global x
x = 211 # Modifies the global variable
update_global()
print(x) # Output: 211
211
Variables as References¶
In Python, variables do not store values directly like in some other languages. Instead, a variable acts as a reference (or pointer) to an object stored somewhere in memory.
This means: A Python variable doesn’t hold the value itself—it holds a reference to the object containing the value.
What Happens During Variable Assignment?¶
- When you assign a value to a variable:
value = 256 # Assigning an integer to variable
Python performs the following steps behind the scenes:
- Creates an
intobject with the value256in memory. - Binds the variable name
valueto the memory location of that object.
- Creates an
So, the variable
valueis not the value256, but a reference to the integer object that holds `256'.
Accessing a Variable¶
When you access the variable
valuePython:- Looks up the reference bound to
value. - Retrieves the actual value from the object that
valuepoints to. - Prints that value.
- Looks up the reference bound to
Variables Are References to Objects¶
To verify this behavior, we can check the memory address of the object that a variable points to using Python’s built-in
id()function:- The
id()function returns a unique integer identifier (based on the object’s memory address). - The output is in decimal (base-10) format.
- The
value = 256 # Assigning an integer to variable
# Print the value
print("Value:", value) # Output: Value: 256
# Print the memory address (decimal)
print("Memory ID (Decimal):", id(value))
# Output (Sample):
# Value: 256
# Memory ID (Decimal): 10765896
Value: 256 Memory ID (Decimal): 10765896
Reference in Python¶
- In Python, variables aren’t like physical boxes that contain values. Instead, they act more like name tags that point to objects stored somewhere in memory.
- A variable → points to → an object → which holds → a value.
- Multiple variables can point to the same object.
- Once no variable points to an object, Python eventually removes it from memory.
How Variable Assignment Works¶
- When you do something like:
x = 42
Here’s what happens behind the scenes:
- Python creates an integer object with the value
42. - Python binds the name
xto that object’s memory location. - When you later use
x, Python looks up the object it points to and retrieves the value.
- Python creates an integer object with the value
Checking the Memory Address¶
- You can use the built-in
id()function to see the unique identity (memory address) of an object:
| Function | Purpose | Example Output |
|---|---|---|
id(obj) |
Returns the object’s memory address (decimal) | 140736839340240 |
hex() |
Converts the decimal address to hexadecimal | 0x7ffde5a2f0f0 |
# Assign a value to a variable
score = 42
# Show memory address in decimal
print(id(score))
# Show memory address in hexadecimal
print(hex(id(score)))
# Output (your values will differ):
# 10759048
# 0xa42b88
11655688 0xb1da08
Reference Counting¶
- Every object in Python keeps track of how many variables (or other objects) are pointing to it.
Key Points:
- One variable → one reference.
- Two variables pointing to the same object → two references.
- If the reference count drops to zero, Python’s garbage collector removes the object.
Example: Multiple References¶
# One variable pointing to an object
var_1 = 42
# Another variable points to the SAME object
var_2 = var_1
print(id(var_1), id(var_2)) # Same memory address for both
# Output: (11655688, 11655688)
# Change var_2 to point to a different object
var_2 = 99
print(id(var_1), id(var_2)) # Now they point to different objects
# Output: (11655688, 11657512)
# Change a as well
var_1 = 0
# Now, original object 42 has zero references and can be destroyed
11655688 11655688 11655688 11657512
Behind the Scenes: Garbage Collection¶
When Python sees that an object has no remaining references, it schedules that object for garbage collection — freeing memory for future use.
You usually don’t need to manage this yourself, but it’s important to understand how it works so you can avoid unnecessary memory usage.