Python Variable

Contents

Python Variables Tutorial: Beginner to Advanced (With Real-Life Examples)

1. Getting to Know Variables in Python

Imagine you have a locker in school. You write your name on it and put your books inside. Later, whenever you want your books, you go to that locker. In Python, a variable is like a locker. You give it a name, and you store some value inside. When you need that value, you call the name again. When you’re writing code, you need a way to store and manage data. That’s where variables come into play. A variable is simply a name given to a value that you want to use in your program. Think of a variable like a label on a box — the box holds some item (your data), and the label (your variable name) tells you what’s inside.

For example, if you want to store the name of a student, you might write something like:

student_name = "Ankit"

Here, student_name is a variable, and it holds the value "Ankit". Whenever you use student_name in your program, Python will know you’re referring to "Ankit".

Variables make your code reusable and readable. Instead of typing the value over and over again, you just reference the variable. Plus, if the value changes, you only have to change it in one place!

2. Creating Variables With Assignments

In Python, creating a variable is as simple as typing the variable name, followed by an equal sign, followed by the value you want to store. This process is called assignment.

Here are a few examples:


name = "Ankit"
age = 24
height = 171.5
is_student = True

In each of these examples, we’re assigning a value to a variable:

  • name stores a string
  • age stores an integer
  • height stores a float (decimal)
  • is_student stores a boolean (True/False)

You don’t need to declare a variable type ahead of time like in other languages (such as C or Java). Python figures it out based on the value you assign. This is one of the reasons why Python is so beginner-friendly!

3. Setting and Changing a Variable’s Data Type

Apart from a variable’s value, it’s also important to consider the data type of the value. When you think about a variable’s type, you’re considering whether the variable refers to a string, integer, floating-point number, list, tuple, dictionary, custom object, or another data type.

Python is a dynamically typed language, which means that variable types are determined and checked at runtime rather than during compilation. Because of this, you don’t need to specify a variable’s type when you’re creating the variable. Python will infer a variable’s type from the assigned object.

You can change the type of a variable simply by assigning it a different type of value:


x = 5          # x is an integer
x = "Hello"    # now x is a string
x = 3.14       # now x is a float

This flexibility can be powerful, but it also requires you to be careful. If you accidentally assign the wrong type, your program might behave unexpectedly.

Real-life example? Imagine you’re storing someone’s phone number in a variable: phone = 9876543210 — Python will treat it as a number. But what if you want to preserve leading zeros or prevent accidental calculations? Then you should store it as a string: phone = "09876543210".

4. Working With Variables in Python

Once you've created a variable, you can start using it throughout your code. You can display it, use it in calculations, combine it with other variables, or pass it into functions. Variables are the building blocks of any Python program.

Let’s say you’re developing a program for a grocery store. You might need to track the price of an item, the quantity being purchased, and the total cost. You can do that easily with variables:


item_price = 20
quantity = 3
total_cost = item_price * quantity
print("Total cost is:", total_cost)

This example shows how variables are used together to perform operations and produce results. Variables are dynamic – you can change their values at any point, and the rest of your code can react accordingly.

Working with variables also includes understanding how Python treats different data types. You might need to convert types using functions like int(), float(), or str() when combining variables in operations.

5. Expressions

In Python, an expression is any valid combination of variables, operators, and values that Python can evaluate to a result. Variables are often part of expressions because they store the data that expressions operate on.

For example:


a = 10
b = 5
result = a + b

Here, a + b is an expression, and the result (15) gets stored in the variable result.

Expressions can be simple, like the one above, or complex, involving multiple variables and operations:


x = 2
y = 3
z = (x + y) * (x - y)

In this case, Python calculates the value of (2 + 3) * (2 - 3) which results in 5 * -1 = -5. Understanding expressions is crucial because most real-world programs involve some kind of computation using variables.

6. Object Counters

An object counter is a type of variable that helps you count how many times something happens. This is very common in programming when you want to track occurrences, repetitions, or specific behaviors.

Let’s take a real-life example. Suppose you’re creating a program that processes user logins. You want to count how many users logged in successfully:


successful_logins = 0

# Simulate three successful logins
successful_logins += 1
successful_logins += 1
successful_logins += 1

print("Total successful logins:", successful_logins)

In this code, we start with successful_logins set to 0. Each time a login is successful, we increment the counter using += 1. This approach is widely used in loops and tracking systems.

7. Accumulators

“Imagine you’re collecting drops of juice in a bottle. Each time a drop falls, you add it to the bottle. That bottle is like an accumulator – it stores the total juice collected.” An accumulator is another useful concept in Python. An accumulator is a variable that keeps adding (or collecting) values over time, usually inside a loop. It “accumulates” results across multiple steps in a program.

For example, if you’re summing up numbers from a list:


numbers = [10, 20, 30, 40]
total = 0

for num in numbers:
    total += num

print("Sum of all numbers:", total)

Here, total is an accumulator. It starts at 0, and in each loop, the current number is added to it. By the end of the loop, it holds the sum of all the numbers.

Accumulators aren’t just for numbers. You can use them to build strings, lists, or any other kind of collection:


words = ["Python", "is", "awesome"]
sentence = ""

for word in words:
    sentence += word + " "

print(sentence.strip())

This pattern is essential when you’re combining data or calculating totals in a loop or over time.

8. Temporary Variables

Temporary variables are used to hold data for a short period, usually within a limited scope like inside a function or loop. These variables serve as placeholders to complete intermediate calculations or store values temporarily before they are used or discarded.

For example, if you're swapping values between two variables, you often use a temporary variable to avoid overwriting data:


a = 5
b = 10

# Swapping values using a temporary variable
temp = a
a = b
b = temp

print("a:", a)
print("b:", b)

Here, temp is a temporary variable. It holds the value of a so that we can assign b to a, and then put the original value of a (stored in temp) into b. Once the swap is done, temp is no longer needed.

Python also allows tuple unpacking to achieve the same without a temporary variable, but the concept is essential when you're performing intermediate steps in calculations.

9. Boolean Flags

Boolean flags are variables that are used to signal a condition—true or false. These variables typically hold values of either True or False and are extremely useful in controlling the flow of a program.

Let’s say you’re writing a program to check if a user has completed a form:


form_completed = False

# Simulate a condition where the form gets completed
user_input = "yes"

if user_input == "yes":
    form_completed = True

if form_completed:
    print("Thank you for completing the form!")
else:
    print("Please complete the form.")

Here, form_completed is a Boolean flag. It starts as False and changes to True when the condition is met. Flags are very helpful when you need to track states or toggle options.

10. Loop Variables

Loop variables are used in loops to keep track of the current item being processed. They act as placeholders for each element in an iterable like a list, tuple, or string.

For instance, in a for loop, the loop variable helps us process one item at a time:


colors = ["red", "blue", "green"]

for color in colors:
    print("Color is:", color)

In this example, color is the loop variable. It takes on each value in the colors list, one at a time. Loop variables can be named anything, but they should be meaningful to enhance code readability.

Loop variables are not limited to for loops. Even in while loops, variables are used to track iteration:


count = 1

while count <= 5:
    print("Count is:", count)
    count += 1

Here, count is a loop control variable that changes in each iteration, affecting when the loop will end.

11. Data Storage Variables

Data storage variables are used to hold data that your program might need to access or modify multiple times. These variables usually store large or critical sets of information like lists, dictionaries, or even complex objects.

Think of a to-do list app. You’d want to store all the tasks in a list so that you can display, update, and delete them as needed:


tasks = ["Finish homework", "Go to the gym", "Buy groceries"]

# Display all tasks
for task in tasks:
    print("Task:", task)

In this example, tasks is a data storage variable. It keeps a collection of strings (tasks) that you can manipulate. You can add tasks with append(), remove them with remove(), or change them using their index.

Storing data in variables is a fundamental concept in programming, especially when the data needs to be reused or shared between functions and modules.

12. Data Storage Variables

Data storage variables are exactly what they sound like — variables that are used to store important data which will be used later in your program. In most cases, these variables store inputs from the user, data fetched from an API, or even values retrieved from a file or database.

For example, let’s say you’re building a student registration form in Python. You can create data storage variables like student_name, email, roll_number, etc., to keep user-entered data. Later on, you can use these values to save into a database, print confirmation, or even send an email.

Data storage variables help keep your logic clean and organized. Instead of hard-coding or repeating data, you just reuse the variable wherever needed. It’s a great way to manage user information, system settings, or configuration parameters throughout your program.

13. Naming Variables in Python

When it comes to writing clean and understandable code, variable names play a huge role. A good variable name should reflect the value it holds or the role it plays in the program. For instance, if a variable stores the age of a user, naming it user_age is much more readable than a or x1.

Python doesn’t enforce naming styles, but following a clear naming convention helps others (and your future self!) understand what’s going on in the code. Whether you’re writing a calculator, a website, or a machine learning model, naming variables well makes debugging, testing, and collaboration easier.

Also, variable names in Python are case-sensitive. That means Name and name are two different variables. So, be careful with capitalization while naming or reusing variables in your code.

14. Rules for Naming Variables

Python has a few basic rules that you must follow when naming variables. If you don’t, your program will throw errors.

  • Variable names must start with a letter (A–Z or a–z) or an underscore (_).
  • The rest of the name can contain letters, digits (0–9), or underscores.
  • You cannot use symbols like @, $, %, or spaces in variable names.
  • Variable names are case-sensitive, meaning Student and student are different.
  • You cannot use Python keywords as variable names (like if, class, return, etc.).

Breaking any of these rules results in a syntax error. So, always make sure your variable names follow Python’s conventions.

15. Best Practices for Naming Variables

While Python doesn’t force you to follow best practices, doing so can make your code more readable and professional. Here are a few important tips:

  • Be descriptive: Use names that describe what the variable stores. For example, use user_score instead of us.
  • Use lowercase letters with underscores: This is known as snake_case and is the preferred style in Python. Example: total_amount
  • Avoid single-letter names: Except for counters or loop variables (like i, j), avoid using single-character names.
  • Stick to consistency: Use the same naming style throughout your project. Don’t mix camelCase and snake_case.
  • Don’t use misleading names: For example, don’t name a variable total if it actually stores a discount.

Following these practices ensures your code looks neat and understandable, not just for you but also for others working with you. This becomes especially useful when collaborating on bigger projects or when coming back to your own code after weeks or months.

16. Public and Non-Public Variable Names

In Python, there's a naming convention that helps indicate whether a variable is meant to be accessed directly or not. While Python doesn’t enforce true privacy like some other languages (such as Java or C++), we use underscore prefixes to signal the intended visibility of a variable.

  • Public variables: These can be accessed from anywhere in your code. You define them with regular names like username or email.
  • Non-public (private) variables: These are meant to be used only within a class or module. You define them using a single underscore prefix, like _password. This tells other developers, “Hey, don’t touch this unless you know what you’re doing.”
  • Name-mangled variables: If you use two underscores like __secret_key, Python will rename this variable internally to avoid accidental access or overrides. This is often used to avoid naming conflicts in subclasses.

These naming conventions help keep your code organized and prevent accidental misuse of internal variables, especially in large projects or class-based programming.

17. Restricted and Discouraged Names

Some variable names in Python are either restricted (you can't use them) or discouraged (you can use them, but you really shouldn't). Let’s break this down.

First, Python has a set of reserved keywords that you absolutely cannot use as variable names. These are special words that have built-in meanings in Python’s syntax, such as if, else, class, return, and so on.

Here's a small list of such keywords:

def, class, return, import, from, if, else, elif, try, except, with, as, while, for, pass, break, continue, in, is, not, or, and

Next, some names are discouraged because they can lead to confusion or override built-in functions. For example, naming a variable list or input is technically allowed, but doing so will override Python’s built-in list() constructor or input() function, which can break your code.

Always check whether a name already has a special meaning in Python before using it. If you’re unsure, it’s a good idea to test in an interactive Python shell.

18. Exploring Core Features of Variables

Python variables offer a lot of flexibility and are quite powerful when compared to variables in many other programming languages. Let’s explore a few core features that make Python variables unique.

  • Dynamically typed: Python doesn’t require you to declare a variable’s type. You just assign a value, and Python figures it out.
  • Memory efficient: Python manages memory automatically using references. When two variables point to the same object, Python won’t duplicate the memory until one of them changes.
  • Reference-based: Variables in Python don’t store values directly. Instead, they hold a reference to an object in memory.
  • Support for any object type: A variable can refer to a number, string, list, dictionary, class instance, or even a function. There’s no limit to what kind of object a variable can reference.
  • Garbage collected: Python automatically frees memory from unused objects using garbage collection, so you don’t have to worry about manual memory management.

These features make Python variables easy to use for beginners and powerful enough for advanced programmers. You can write clean, readable code without needing to worry about complex type declarations or memory issues.

19. Variables Hold References to Objects

This is one of the most important things to understand about Python variables. In Python, variables do not store the actual value directly. Instead, they store a reference to an object in memory.

Let’s say you write:

x = [1, 2, 3]

The variable x doesn’t actually hold the list [1, 2, 3]. It holds a reference to the list object stored somewhere in memory. If you then do:

y = x

Now y also refers to the same list object. Any changes made using y will reflect in x as well, because they are both pointing to the same memory location.

This concept is especially important when working with mutable objects like lists, dictionaries, or custom objects. It’s always good to be aware of whether you're copying the reference or the value to avoid unexpected behavior.

20. Variables Have Dynamic Types

One of Python’s most beginner-friendly and flexible features is that variables have dynamic types. This means the data type of a variable is determined at runtime, and you don’t need to declare it explicitly. You can assign any type of value to a variable without mentioning what kind of data it will hold.

Let’s take a look:

x = 5 # x is an integer
x = "Hello" # now x is a string
x = [1, 2] # now x is a list

As you can see, Python doesn’t complain when you change the data type of x. You can first store a number, then a string, and later a list—all in the same variable. That’s the power of dynamic typing.

However, while this offers flexibility, it also requires you to be careful. If you accidentally change a variable’s type in your code, it can lead to bugs that are hard to catch, especially in large programs. That’s why writing clear and meaningful variable names, along with good comments, becomes essential.

21. Variables Can Use Type Hints

Although Python is dynamically typed, it also supports something called type hints (also known as type annotations). These are not enforced by the interpreter, but they help tools like mypy or IDEs like VS Code to provide better code analysis, auto-completion, and bug detection.

Here’s an example of using type hints:

age: int = 25
name: str = "Ankit"
is_active: bool = True

With this, you're telling Python (and other developers) what type of data each variable is expected to hold. It doesn’t stop you from assigning something else (like name = 123), but it does make your code cleaner and easier to debug.

You can also use type hints in function parameters and return values:

def greet(name: str) -> str:
    return f"Hello, {name}"

Type hints are optional, but in larger projects or collaborative environments, they can save a lot of time and confusion.

22. Using Complementary Ways to Create Variables

In Python, variables can be created in a variety of ways beyond the usual variable = value style. These methods help make your code cleaner, shorter, and sometimes even faster. Let’s explore a few of these complementary techniques.

  • Tuple unpacking: Assign multiple values at once.
  • Swapping variables: Python lets you swap values without needing a temporary variable.
  • Using built-in functions: Sometimes functions return multiple values, and you can assign them directly.

Here’s an example that shows tuple unpacking and swapping:

a, b = 10, 20 # tuple unpacking
a, b = b, a # swapping values

Another use case is with functions:

def get_coordinates():
    return (45.0, 90.0)

lat, long = get_coordinates()

These tricks help reduce lines of code and improve readability. When used properly, they make Python programming feel more natural and efficient.

23. Parallel Assignment

One of Python’s coolest and most readable features is parallel assignment. It lets you assign values to multiple variables at the same time using a single line of code. This not only looks cleaner but is also more efficient in many cases.

Here’s how it works:

x, y, z = 1, 2, 3

In this example, x gets 1, y gets 2, and z gets 3. No need to write three separate lines. It’s like Python is distributing the values for you!

This is especially useful when working with functions that return multiple values, or when iterating over two lists at the same time using the zip() function.

For example:

names = ["Ankit", "Sohan", "Rita"]
ages = [24, 28, 22]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

Parallel assignment is clean, expressive, and aligns well with Python’s philosophy of writing code that reads almost like English.

24. Iterable Unpacking

In Python, iterable unpacking is a powerful way to assign values from any iterable—such as lists, tuples, or strings—into multiple variables at once. This technique enhances code readability and often simplifies logic.

For example, suppose you have a list of values:

numbers = [10, 20, 30]
a, b, c = numbers

Here, a gets 10, b gets 20, and c gets 30. Python automatically unpacks the values based on their order in the iterable.

You can also use the * operator to capture multiple values into a single variable:

x, *y, z = [1, 2, 3, 4, 5]

In this case, x = 1, y = [2, 3, 4], and z = 5. This is helpful when you only care about the first and last values, but want to keep the rest grouped.

25. Assignment Expressions

Assignment expressions, also known as the walrus operator (:=), were introduced in Python 3.8. They allow you to assign a value to a variable as part of an expression.

This is particularly useful when you want to assign a value and use it right away, such as inside loops or conditionals.

if (n := len("Python")) > 5:
    print(f"Length is {n}, which is more than 5")

In this example, n gets assigned the length of "Python" (which is 6), and we use it immediately in the condition check. Without the walrus operator, you'd need to split this into two separate lines.

It's a great feature when used properly, but don’t overuse it—it can sometimes make your code harder to read.

26. Understanding Variable Scopes

In Python, the scope of a variable refers to the part of the code where that variable is accessible. There are four main types of scope in Python, often remembered by the LEGB rule:

  • Local: Variables defined within a function and only accessible there.
  • Enclosing: Variables in the local scope of any enclosing function.
  • Global: Variables defined at the top-level of a script or module.
  • Built-in: Names preassigned in Python, like len(), print(), etc.

Here’s an example showing local and global scope:

x = "global"

def func():
    x = "local"
    print(x)

func()      # Output: local
print(x)    # Output: global

Understanding scopes is crucial when you work with larger projects or nested functions, as variable conflicts or unexpected overwrites can lead to bugs.

27. Global, Local, and Non-Local Variables

Python lets you explicitly declare global and non-local variables when you want to access or modify variables outside the current scope.

Global variables are declared outside any function and can be used anywhere. However, to modify a global variable inside a function, you must declare it with the global keyword.

count = 0

def increment():
    global count
    count += 1

Non-local variables come into play when working with nested functions. They allow you to modify a variable from the nearest enclosing scope (but not global).

def outer():
    value = "outer"

    def inner():
        nonlocal value
        value = "inner"

    inner()
    print(value)  # Output: inner

Using global and non-local variables gives you more control over variable access, but be cautious. Overusing them can make your code harder to understand and maintain.

28. Class and Instance Variables (Attributes)

In object-oriented programming with Python, variables can belong either to a class or to an instance of that class. These are referred to as class variables and instance variables (also known as attributes).

Class variables are shared by all instances of the class. They are defined within the class but outside any method. When you change a class variable, the change reflects across all instances—unless an instance overrides it.

class Car:
    wheels = 4  # Class variable

    def __init__(self, brand):
        self.brand = brand  # Instance variable

car1 = Car("Toyota")
car2 = Car("Honda")

print(car1.wheels)  # Output: 4
print(car2.wheels)  # Output: 4

Instance variables are unique to each object or instance. They’re usually defined using self within the constructor method __init__(). Each object can have different values for its instance variables.

print(car1.brand)  # Output: Toyota
print(car2.brand)  # Output: Honda

If you change wheels in the class, all cars will reflect the change unless you override the class variable for a specific object. Here's an example:

Car.wheels = 6
print(car1.wheels)  # Output: 6
print(car2.wheels)  # Output: 6

But if you do car1.wheels = 8, it only changes for car1 because it now has its own instance variable named wheels that shadows the class variable.

Understanding this difference is important when designing scalable class-based architectures in Python. It helps manage data either shared across all objects or kept uniquely per instance.

29. Deleting Variables From Their Scope

Sometimes, you may want to remove a variable from memory, especially when you're done using it or if you want to free up resources. In Python, you can delete a variable using the del statement.

For example:

name = "Ankit"
print(name)  # Output: Ankit

del name
# print(name)  # This will raise an error: NameError: name 'name' is not defined

The del statement doesn’t just set the variable to None; it removes the reference to the object completely from the current scope. Once deleted, the variable no longer exists unless it's recreated.

You can also delete elements from a list or dictionary:

my_list = [1, 2, 3]
del my_list[1]
print(my_list)  # Output: [1, 3]

Or delete keys from a dictionary:

person = {"name": "Ankit", "age": 24}
del person["age"]
print(person)  # Output: {'name': 'Ankit'}

Be careful when using del. If you delete something and try to access it later, your code will crash. Use it only when you’re sure that the variable or element is no longer needed.

30. Conclusion

Variables are the building blocks of any programming language, and in Python, they offer a simple yet powerful way to store and manage data. From basic assignments to advanced concepts like class attributes, scope, dynamic typing, and unpacking, Python makes working with variables intuitive and flexible.

Throughout this tutorial, we’ve explored not just how to declare and use variables, but also why and where they matter. Whether it’s naming conventions, memory management, or best practices in writing readable code, each concept plays a vital role in writing clean, maintainable, and efficient Python scripts.

Always remember—your variables are not just for the machine, they are also for you and other humans reading your code. Choosing the right names, using the right types, and structuring them well will make you a better Python developer.

Keep experimenting, stay consistent, and enjoy your Python journey!

31. Frequently Asked Questions

Q1. Do I need to declare the data type of a variable in Python?

No, Python is a dynamically typed language. You don’t need to declare the data type when assigning a value to a variable. Python automatically understands the type based on the assigned value.

Q2. Can I change the type of a variable after it is defined?

Yes! Since Python is dynamically typed, you can assign a new value of a different type to the same variable. For example:

x = 10     # integer
x = "Ten"  # now it's a string

Q3. What happens if I use the same variable name in different scopes?

Python follows the LEGB (Local, Enclosing, Global, Built-in) rule to determine variable scope. If a variable exists in a local scope, it overrides the same-named variable in the global scope. So, the value depends on where you're accessing it from.

Q4. What’s the difference between instance and class variables?

Instance variables are specific to each object of a class, while class variables are shared across all instances. Instance variables are declared inside methods using self, and class variables are defined directly inside the class.

Q5. Can I delete a variable in Python?

Yes, using the del keyword. Once deleted, the variable is removed from memory and is no longer accessible unless redefined.

Q6. What are some best practices for naming variables?

- Use descriptive names that clearly represent the value or purpose.
- Follow the snake_case convention for regular variables.
- Avoid using Python built-in names (like list, str).
- Don’t start variable names with numbers or special characters.

Q7. How can I check the type of a variable?

You can use the type() function to check what data type a variable holds:

my_var = 123
print(type(my_var))  # Output: <class 'int'>

If you’ve made it this far, congratulations! You now know more about Python variables than most beginners. Keep practicing and building projects to reinforce what you've learned.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x