Python Variables are fundamental for storing and managing data in Python Programming. They generally act as the containers that basically hold values that allow the developers to efficiently reference and manipulate data without directly accessing the memory addresses. In this Python Variables tutorial, you will learn everything about the variables from assigning to more advanced concepts and various use cases like dynamic typing, type casting of variables, object reference, memory management, and many more that will generally help you to write cleaner and more concise code.
Whether you are a beginner who wants to get started with the basics of Python to get a reputable job or you are an experienced programmer who is looking to brush up on concepts like the scope of a variable or the use of variables in regular expressions, this tutorial will help you to do so.
Table of Contents:
What are Variables in Python?
Python variables are generally symbolic names that simply act as references to memory locations where the data is being stored. They allow them to store, retrieve, and manipulate different types of data like integers, strings, floats, and more without the need to directly manage the memory addresses. Also, Python doesn’t require any explicit data type declarations as variables in Python are dynamically typed and can adapt to their type during the program execution.
In simple terms, whenever you assign any value to a variable in Python, its interpreter automatically creates an object to hold that value and references it through the variable name.

Example:
Output:

Rules for Naming Variables in Python
Proper naming of the Python variables is very important for writing clean, readable, and maintainable Python code. Here we have mentioned the important rules that simply ensure that your code runs without errors.
1. Start with a Letter or Underscore (_)
The name of every variable in Python must begin with either a letter (A-Z, a-z) or an underscore (_).
Company = “Intellipaat’
name = "Ayaan"
_age = 24
2. Do Not Start with a Number
In Python, you cannot start variable names with a digit (0-9).
Example of invalid variable:
2num = 34 # Error! Invalid variable name
3. Use Only Letters, Numbers, and Underscores
Variable names can only contain alphabets, numbers, and underscores (_). Special characters like @, #, or $ are not allowed in Python.
Example:
product_name = "Laptop"
product123 = "Phone"
4. Python Variable Names are Case-Sensitive
Variables in Python are case sensitive such that Name, name, and NAME will all be considered as three different variables.
Example:
name = "Learn"
Name = "Python Variables"
print(name) # output - Learn
print(Name) # output - Python Variables
#This code demonstrates the case-sensitive nature
5. Avoid Using Reserved Keywords
The name of a variable cannot have Python keywords such as for, if, else, class, etc.
Example of invalid variable:
for = "Invalid" # Error! "for" is a reserved keyword
6. Use Descriptive Names
Always choose meaningful variable names that best represent the value or purpose of the variable for easier readability of your code.
Example:
student_age = 20
product_price = 100.50
By learning these best practices and Python variable naming conventions, your code will remain tidy, optimized, and in compliance with the best coding standards.
Master Python Programming!
Learn, code, and create with Python. Start now!
Assigning Values to Python Variables
Assigning Values to Python variables must always be defined with an assignment through an equal sign (=), and then its value is placed afterward. Python even doesn’t have a necessity for declaring a variable’s data type, unlike most used in programming languages.
1. Basic Assignment
In Python, no declaration of a variable in memory is explicitly required. All you have to do is use an assignment with an equal sign (=) and Python will sort out the rest.
Example:
Output:

2. Dynamic Nature of Python
Python is a dynamically typed language, i.e., it automatically detects the type of the assigned variable.
Example:
Output:

Here we have used the type function for printing the type of variables which you will learn later in further sections
Multiple Variable Assignment
In Python, we can assign multiple variables to a single value or maybe with different values.
1. Multiple Variable Assignment with the same value
We can assign a single value to multiple variables in the following manner:
Output:

2. Multiple Variable Assignment with different value
Also, we can assign multiple values to multiple variables in the following manner:
Output:

Type Casting a Variable
When we convert a value from one data type into another data type, this process is called type casting a variable. In Python, there are a lot of functions for casting a variable including int(), float(), str(), etc.
Basic Casting Functions
- int(): It converts the given value into an integer.
- float(): It converts the given value into float or decimal.
- str(): It converts the given value into a string.
Example:
Output:

Getting the Type of Variable in Python
In Python, you can get the data type of a variable with the ‘type()’ function in the following manner:
Output:

Scope of a Variable
Not all variables in Python may be accessible at all locations. This depends on where these variables were declared. The scope of the variable defines where in the program the variable will be accessible. The scope can be either local or global. So, let’s learn about local and global variables in Python.
1. Local Variables in Python
A variable that is declared inside a Python function or module can only be used in that specific function or Python Module. This kind of variable is known as a local variable.
Example:
Output:

In this example, when the variable a is declared the second time inside the function named some_function, it becomes a local variable. Now, if we use that variable inside the function, there will be no issues, as we can see in the output of the second print(a); it prints the value assigned to an in the function, that is, “Intellipaat”.
Whereas, when we try to print the value outside the function, it prints the value assigned to it outside the function, as we can see in the output of the first and third print(a); it prints 100.
2. Global Variables in Python
On the other hand, Python global variables are variables that can be used anywhere within your program without needing to be declared every time they are needed.
Example:
Output:

Here, in this example, we have declared variable a as a global variable and changed its value inside of a function while printing outside of it; it will print its changed value, as can be seen from print(a). Since variable a was declared globally, it can also be used outside its function scope.
Constants in Python
A constant is a type of variable that holds values that cannot be changed. In reality, we rarely use constants in Python. Constants are usually declared and assigned to a different module/file.
Example:
Output:

Then, they are imported to the main file.
Output:

Python Class Variables
In Python, a class variable is shared by all the object instances of the class. They are declared when the class is constructed and not in any of the methods of the class. Since in Python, these class variables are owned by the class itself, they are shared by all instances of that class.
Example:
Output:

Here, the variable lang_name is given the value “python”.
Python Private Variables
In Python, ‘Private’ instance variables can’t be accessed except inside an object; they do not practically exist. However, most Python coders use two underscores at the beginning of any variable or method to make it private.
Example:
Output:

A variable __intellipaat will be treated as a non-public or a private variable.
Object Reference in Python
In Python, an object reference is a variable that stores the address of an object rather than the actual object itself. When we create a variable and assign it an object, the variable becomes a reference to that object.
Let’s understand this with a real-life example:
Suppose we declare a variable as x=5 in Python,
x=5
print(x)

Python generates an object to represent the value 5 when x = 5 is executed and references this object.
Now, if we want to assign y = a,

Now, y is also pointing to the same reference as a, this is called the shared reference.
If we assign x = “Greeks”, and y= “Computer”

Explanation:
Now, x is referencing “Greeks”, y is referencing “Computer”, and 5 is no longer referencing any variable, and becomes eligible for garbage collection.
Delete a Variable Using del Keyword
Python provides a feature to delete a variable when it is not in use, so as to free up space. Using the command del ‘variable name’, we can delete any specific variable.
Learn Python, Shape Your Future!
Enroll now and start coding your way to success with Python!
Example:
Output:

If we run the above program, the Python interpreter will throw an error as ‘NameError: name a is not defined’ in the second print (a) since we have deleted the variable a using the del command.
Key Takeaways:
- Python variables store references to objects rather than the actual themselves.
- If a variable is not specifically modified, it has no effect on other variables that reference the same object.
Mutable vs Immutable Variables
In Python, all variables reference an object in memory and objects can be either mutable or immutable This generally determines whether values can be changed after creation. Having knowledge about this concept can help you prevent any unexpected behavior in your code.
Type |
Definition |
Examples |
Mutable |
Objects that allow value changes without changing the reference. |
Lists, Dictionaries |
Immutable |
Objects whose value cannot be changed after creation. |
Strings, Tuples, Integers |
1. Mutable Variables
They store the objects that can be modified and changes happen directly to the object without needing reassignment.
Output:

2. Immutable Variables
They store objects that cannot be modified. Any “change” creates a new object reference.
Example:
Output:

Variable Scope in List Comprehensions and Lambdas
Understanding the working of variables in concepts like list comprehensions and lambda functions in Python is very important for gaining a proficiency in Python Programming. These constructs often operate within a particular scope that may lead to unexpected behavior if misunderstood.
1. List Comprehensions and Variable Scope
In Python, a list comprehension contains its own scope (namespace) for its variables. Any variable defined in a list comprehension can only be accessed in that local scope and will not override any variable defined in an outer scope.
Example: Local Scope of List Comprehensions
Output:

Explanation:
- The x inside the list comprehension does not affect the x = 10 defined outside.
- Python isolates the variable inside the list comprehension to prevent accidental overwrites.
2. Lambda Functions and Variable Scope
Lambda functions generally inherit the scope from the enclosing function. They typically capture the variable references which means that they can use the variables that are defined outside their immediate scope but their behavior can be influenced by the mutable data types.
Example: Lambda Function with Outer Scope Variable
Output:

Explanation:
- The lambda function captures the current value of x from the enclosing scope.
- Any subsequent change to x will affect the lambda function if x is mutable.
Advanced Variable Types in Python
Variables in Python are not limited to storing only basic data types like characters, floats, and integers. Below we have discussed some of the advanced variable kinds that you should know:
1. Complex Numbers
Python has native support for complex numbers through the complex data type. They are written in the form a + bj, where a and b are real numbers and j is the imaginary unit.
Example:
Output:

2. Byte Variables
The bytes and byte array types are required for working with binary information. They are useful in file I/O and in networks.
Example:
Output:

3. Frozen Sets
These are immutable collections, making them hashable and hence usable as dictionary keys or elements of a set.
Example:
Output:

Python Variables and Asynchronous Programming
You need to be cautious while handling Python variables in asynchronous programming, especially with concurrent operations and shared states. Always remember these:
1. Independent Variable State
Every coroutine possesses its variable state that generally prevents accidental interference between tasks.
Example:
Output:

2. Shared Variables
Apply synchronization primitives like asyncio. Lock when shared variables are accessed by multiple coroutines.
Example:
Output:

Using Variables in Regular Expressions
The “re” module of Python can dynamically insert variable values into a regular expression, allowing for increased flexibility in pattern matching.
1. Basic Usage:
Insert variables into a pattern using f-strings
Example:
Output:

2. Dynamic Patterns
You can use the dynamic patterns when you want to validate user inputs and you want to extract customized text patterns from large datasets.
Example:
Output:

Comparing Python Variables with Other Languages
Here we have compared Python with multiple different programming languages in order to check how Python typically handles variables compared to these languages and what makes Python different from other languages.
Feature |
Python |
Java |
C++ |
JavaScript |
Declaration |
Dynamic (x = 10) |
Explicit (int x) |
Explicit (int x) |
Dynamic (let x) |
Memory Management |
Automatic (Garbage Collection) |
Manual |
Manual |
Automatic |
Type Handling |
Duck Typing |
Strong Typing |
Strong Typing |
Dynamic Typing |
Variable Scope |
Local, Global, Nonlocal |
Block-Level |
Block-Level |
Block-Level |
Why Python Stands Out:
- No need for explicit data type declaration.
- Efficient garbage collection and memory management.
- Dynamic typing reduces boilerplate code while maintaining flexibility.
Some Practical Examples of Python Variables
1. Adding two numbers
We can use the + operator, we can add two numbers in Python.
Example:
Output:

2. Find the Maximum of two numbers in Python
We can use the max() function to find the maximum of two numbers in Python.
Example:
Output:

3. Count characters of a String
We can use len() function to count characters in a String.
Example:
Output:

Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
With this, you have come to the end of this Python Variable Tutorial. Understanding and working with Python variables is a very important step in order to become a proficient Python programmer. In this tutorial, you have learned everything from the naming convention of Python variables, assigning values, and typecasting to advanced topics like local variables, global variables, and constants.
Mastering how to use and manage the different types of variables in Python will simply improve your ability to write structured and maintainable code.
Now if you want to dive even deeper, consider enrolling in an advanced Python programming course to enhance your skills and unlock new opportunities in the world of programming.
FAQs
What is a variable in Python, and why is it important?
A Python variable is a symbolic name for storing values or data. A variable is a reference to a memory location, and it makes it easy to store, access, and manipulate data in a program. Python variables enable one to write programs efficiently and effectively.
How do you declare a variable in Python?
To declare a variable in Python, assign a value with the use of the = operator but not declaring a variable type. Python will automatically assign a variable type according to the value assigned to it.
What are the naming rules for Python variables?
- A name of a variable must begin with a letter or an underscore (_)
- It cannot have spaces or special characters (other than _)
- It also cannot be a keyword (e.g., if, while
- They are case-sensitive which means “myVar” and “myvar” are not equivalent
What are mutable and immutable variables in Python?
Mutable Variables are those that can change their value without producing a new one (e.g., lists, dictionaries) whereas Immutable Variables are the ones that after being defined, cannot be changed in value (e.g., strings, integers, tuples).
What is variable scope in Python?
Variable scope defines where a variable can be accessed or modified:
- Local Scope: Inside a specific function
- Global Scope: Accessible throughout the entire program
Our Python Courses Duration and Fees
Cohort starts on 23rd Mar 2025
₹20,007