Intensity Coding
  • HOME
  • TUTORIALS
    • Python
    • Natural Language Processing
    • Generative AI
  • ABOUT US
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer

Python

Variables in Python

Python
Python
  • Introduction To Python
  • Write Your First Python Program
  • Indentation And Comments in Python
  • Variables in Python
  • Data Types in Python
  • Booleans and Number in Python
  • Operators in Python
  • Mutable Vs Immutable Objects And Collection in Python
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Control Statements
  • Python Functions
  • Python Lambda Functions
  • Python Exception Handling
  • Python File Handling
  • Python Modules
  • Python Package and PIP
  • Python Keywords
  • Python Built In Functions
  • Introduction To Object Oriented Programming Python
  • Python Classes and Objects
  • Python Inheritance
  • Python Encapsulation
  • Python Regular Expressions (RegEx)
  • Python JSON
  • Python Datetime

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.
In [ ]:
# Variable assignment
my_variable_1 = 42
print(my_variable_1)
42

Variables In Python.png

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).
In [ ]:
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¶

In [ ]:
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.¶

In [ ]:
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.¶

In [ ]:
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.
In [ ]:
# Valid Name
myvariable = "intensity"
my_variable = "intensity"
_my_variable = "intensity"
myVariable = "intensity"
MYVARIABLE = "intensity"
myvariable2 = "intensity"
In [ ]:
# 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
In [ ]:
# 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.
In [ ]:
# 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
In [ ]:
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.
In [ ]:
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.
In [ ]:
coordinates = (3, 4)
x, y = coordinates  # Unpack the tuple into variables

Print the Variables¶

In [ ]:
x = "How are you ?"
print(x)
How are you ?
In [ ]:
# You can put multiple variables, separated by a comma in print()
x = 1
y = 2
z = 3
print(x, y, z)
1 2 3
In [ ]:
# You can use + operator to print multiple variables in print()
x = "1 "
y = "2 "
z = "3 "
print(x + y + z)
1 2 3 
In [ ]:
# For numbers the + character works as a mathematical operator
x = 3
y = 1
print(x + y)
4
In [ ]:
# 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'
In [ ]:
# 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
In [ ]:
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.
In [ ]:
# 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.
In [2]:
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¶

In [ ]:
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¶

In [ ]:
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:

    1. Creates an int object with the value 256 in memory.
    2. Binds the variable name value to the memory location of that object.
  • So, the variable value is not the value 256, but a reference to the integer object that holds `256'.

Accessing a Variable¶

  • When you access the variable value Python:

    • Looks up the reference bound to value.
    • Retrieves the actual value from the object that value points to.
    • Prints that value.

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.
In [ ]:
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:

    1. Python creates an integer object with the value 42.
    2. Python binds the name x to that object’s memory location.
    3. When you later use x, Python looks up the object it points to and retrieves 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
In [6]:
# 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¶

Intensity Coding.png

In [4]:
# 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.

Category
Python Natural Language Processing Generative AI
Tag's
Python Natural Language Processing

Quick Links

  • Home
  • Tutorials
  • About Us
  • Contact Us

Tutorials

  • Python
  • Natural Language Processing
  • Generative AI

Tags

  • Python
  • Natural Language Processing

About Intensity Coding

  • Intensity Coding is your learning hub for Data Science, Machine Learning, Deep Learning, NLP, and Generative AI. From beginner to expert level, we offer clear tutorials, real-world examples, and up-to-date insights. Our content simplifies complex topics to help you grow in your AI journey.
Intensity Coding

© 2025 Intensity Coding. All Rights Reserved.

Privacy Policy Terms and Conditions Disclaimer