Technical Roadmap

What is a variable in Python with example

In this section, we will learn about the basic building blocks of Python programming: Variables. We will learn how Python stores information, the rules for naming these storage spaces, and why Python handles data differently than languages like C++ or Java.

What is a Variable?

A variable is a reserved location in memory where we store our values. In Python, you can think of a variable as a label attached to an object or value. When you assign a value to a name, you are creating a reference to that data in the computer's memory.

💡 The Logicoria Tip

A variable is like a container that holds our values. Think of it as a bucket with a name, and you put some value in it.

Dynamic Typing in Python

Python is dynamically typed. This means you don't need to declare the type of data a variable will hold (like int or String). Python figures it out automatically based on the value you provide.

For example, you can change a variable's content at any time:

Python
# x starts as an integer
x = 27

print(x)

Now x changes to a string
x = "Logicoria"

print(x)
Output
27
Logicoria

Comparing Variables: Python vs. Others

Feature Python C++ / Java
Declaration Created automatically on assignment. Must be explicitly declared (e.g., int x;).
Data Type Dynamic (can change during runtime). Static (fixed once declared).
Memory Variable is a reference/pointer to an object. Variable is a named memory location (container).
Syntax Simple: x = 5 Strict: int x = 5;

Interview/Exam Tip

  • Memory Management: In Python, if a variable is no longer being used, its memory is automatically cleared by a process called Garbage Collection.
  • The id() Function: Use the id(variable_name) function to find the exact memory address of where your data is stored.
💡 The Logicoria Tip

Always use descriptive names! Instead of a = 3.14, use pi_value = 3.14. It makes your code easier for other humans (and your future self) to read.