DEV Community

Cover image for Python Variables: A Complete Beginner's Guide with Examples & Best Practices
Satyam Gupta
Satyam Gupta

Posted on

Python Variables: A Complete Beginner's Guide with Examples & Best Practices

Python Variables: Your Ultimate Guide to Storing Data and Building Code

Welcome, future coders! If you're taking your first steps into the incredible world of Python programming, you've undoubtedly encountered the term "variable." It’s one of those fundamental concepts that forms the very bedrock of writing code, not just in Python, but in every programming language out there.

But what exactly are variables? Why are they so crucial? And how can you use them effectively to write clean, powerful, and efficient Python code?

This comprehensive guide is designed to answer all those questions and more. We'll move from the absolute basics to some more nuanced concepts, all while keeping things engaging and practical. We'll use real-world analogies, write plenty of code examples, and discuss best practices that will set you on the path to becoming a proficient Python developer.

So, grab a cup of coffee, fire up your favorite code editor, and let's demystify Python variables together.

What is a Variable? The Digital Lunchbox
Let's start with a simple analogy. Imagine you have a lunchbox. This lunchbox has a label on it: "My Sandwiches." You open it up, put a ham and cheese sandwich inside, and close it. Now, whenever you or anyone else sees the lunchbox labeled "My Sandwiches," they know exactly what’s inside without having to open it first.

A variable in programming is exactly like that lunchbox.

The Variable Name is the label ("My Sandwiches").

The Assignment Operator (=) is the act of placing the sandwich inside and closing the lid.

The Value is the actual ham and cheese sandwich itself.

In technical terms, a variable is a named location in your computer's memory that is used to store data. You give this location a friendly, human-readable name so that you can easily refer to the data stored there, access it, and manipulate it throughout your program.

The beauty of variables is that they are reusable. You can change what's inside the lunchbox anytime you want. Maybe tomorrow you'll put a salad in it. The label stays the same, but the contents change.

python

The lunchbox is created and a sandwich is placed inside

my_sandwiches = "Ham and Cheese"

Later, we can change what's in the lunchbox

my_sandwiches = "Chicken Salad"

print(my_sandwiches) # This will now output: Chicken Salad
How to Declare a Variable in Python: It Couldn't Be Easier
One of the reasons Python is so beloved by beginners and experts alike is its simplicity and readability. This is perfectly exemplified in how you create, or "declare," a variable.

You declare a variable by simply giving it a name and assigning a value to it using the equals sign =.

The syntax is beautifully straightforward:
variable_name = value

Let's see it in action:

python

Declaring a variable 'message' and assigning it a string value

message = "Hello, World!"

Declaring a variable 'score' and assigning it an integer value

score = 100

Declaring a variable 'pi' and assigning it a float value

pi = 3.14159

Declaring a variable 'is_learning' and assigning it a boolean value

is_learning = True
Notice that we didn't have to tell Python what type of data (text, number, etc.) we were storing. Python figured that out automatically at the moment of assignment. This feature is called dynamic typing, and it makes writing code faster and more flexible. We'll talk more about data types in a moment.

Multiple Assignment: Python's Party Trick
Python has some convenient shortcuts. One of them is the ability to assign values to multiple variables simultaneously.

python

Assigning multiple values to multiple variables, one-by-one (the long way)

a = 1
b = 2
c = 3

Assigning the same value to multiple variables at once

x = y = z = 10

Now x, y, and z all hold the value 10

Assigning different values to multiple variables in one line (Tuple Unpacking)

name, age, occupation = "Alice", 30, "Developer"

name is "Alice", age is 30, occupation is "Developer"

This last trick is incredibly useful for swapping values between variables without needing a temporary placeholder.

python
a = 5
b = 10

The classic way requires a temp variable

temp = a
a = b
b = temp

The Pythonic way is clean and elegant

a, b = b, a
print(a) # Output: 10
print(b) # Output: 5
Understanding Data Types: What's in the Box?
While you don't have to explicitly declare types, the data itself always has a type. The type defines what kind of operations can be performed on the data. You can check the type of any variable using the type() function.

Python has a rich set of built-in data types. Let's explore the most common ones you'll use with variables.

  1. Numeric Types Integers (int): Whole numbers, positive or negative. E.g., 10, -5, 1024.

Floating-Point (float): Numbers with a decimal point. E.g., 3.14, -0.001, 2.0.

Complex Numbers (complex): Numbers with a real and imaginary part (less common for beginners). E.g., 3+4j.

python
year = 2023 # int
temperature = -5.5 # float
print(type(year)) # Output:
print(type(temperature)) # Output:

  1. Text Type String (str): A sequence of characters (text) enclosed in single or double quotes. E.g., "Hello", 'Python', "123" (this is text, not a number).

python
greeting = "Good morning!"
language = 'Python'
print(type(greeting)) # Output:

  1. Boolean Type Boolean (bool): Represents truth values. It can only be True or False (note the capitalization). Essential for control flow and logic.

python
is_rainy = False
is_sunny = True
print(type(is_sunny)) # Output:

  1. Sequence Types List (list): An ordered, mutable (changeable) collection of items. Items can be of different types. Defined with square brackets [].

Tuple (tuple): An ordered, immutable (unchangeable) collection of items. Defined with parentheses ().

Range (range): An immutable sequence of numbers, commonly used for looping a specific number of times in for loops.

python
fruits_list = ["apple", "banana", "cherry"] # list
coordinates_tuple = (10.0, 20.5) # tuple
number_sequence = range(5) # range (0, 1, 2, 3, 4)
Checking and Casting Types
You can convert between types using functions like int(), float(), str(), etc. This is called type casting.

python

This is a string

num_str = "100"
print(type(num_str)) #

Cast it to an integer to do math

num_int = int(num_str)
result = num_int * 2 # 200

Cast it back to a string to concatenate with other text

result_str = str(result)
final_message = "The result is " + result_str
print(final_message) # The result is 200
Understanding data types is critical because it prevents errors. You can't add a string to an integer without first converting one of them.

python

This will cause a TypeError

age = 30
message = "You are " + age + " years old."

This is the correct way

message = "You are " + str(age) + " years old."
Variable Scope: Knowing Where Your Lunchbox is Valid
Where you declare your variable matters. Not every variable can be seen or accessed from every part of your code. The context in which a variable is defined is known as its scope. There are two fundamental types of scope in Python.

  1. Local Scope A variable created inside a function belongs to the local scope of that function. It can only be used inside that function. It is created when the function is called and destroyed when the function finishes execution.

python
def my_function():
local_var = "I am local" # This variable is local to my_function
print(local_var) # This works

my_function()
print(local_var) # This will cause a NameError! 'local_var' is not defined outside the function.

  1. Global Scope A variable created in the main body of your Python code is a global variable. It belongs to the global scope and can be used by anyone, both inside and outside of functions.

python
global_var = "I am global" # This is a global variable

def my_function():
print("Inside function:", global_var) # I can access the global variable here

my_function()
print("Outside function:", global_var) # And here
The global Keyword
What if you want to modify a global variable from inside a function? You have to use the global keyword.

python
counter = 0 # This is a global variable

def increment():
global counter # Tell Python we want to use the global 'counter'
counter += 1
print("Inside function:", counter)

increment() # Output: Inside function: 1
increment() # Output: Inside function: 2
print("Outside function:", counter) # Output: Outside function: 2
Best Practice: While global variables are useful, overusing them can make code difficult to debug and maintain. It's often better to pass variables as arguments to functions and return results, keeping your functions self-contained and predictable.

Mutable vs. Immutable Objects: A Critical Distinction
This is a more advanced but incredibly important concept in Python. The mutability of an object determines whether its value can be changed after it is created.

Immutable Object: An object whose state (value) cannot be modified after it is created. If you try to change it, Python will actually create a new object.

Types: int, float, str, bool, tuple.

Mutable Object: An object whose state can be modified after it is created.

Types: list, dict, set.

Why does this matter? It affects how variables behave when you assign them to each other or pass them to functions.

python

Immutable Example (int)

a = 10
b = a # 'b' gets a copy of the value in 'a'
b = 5 # This change does NOT affect 'a'
print(a) # Output: 10
print(b) # Output: 5

Mutable Example (list)

list_a = [1, 2, 3]
list_b = list_a # 'list_b' refers to the SAME list in memory as 'list_a'
list_b.append(4) # Modifying the list through 'list_b'
print(list_a) # Output: [1, 2, 3, 4] -> 'list_a' is also changed!
print(list_b) # Output: [1, 2, 3, 4]
To create a true independent copy of a mutable object like a list, you need to explicitly copy it.

python
import copy

list_a = [1, 2, 3]
list_b = list_a.copy() # or list_b = copy.copy(list_a) for shallow copy
list_b.append(4)
print(list_a) # Output: [1, 2, 3] -> Unchanged!
print(list_b) # Output: [1, 2, 3, 4]
Best Practices and Naming Conventions
Writing code that works is one thing; writing code that is clean, readable, and maintainable is another. Following naming conventions is a key part of being a professional developer.

Rules for Python Variable Names:
Can only contain: letters (a-z, A-Z), digits (0-9), and underscores (_).

Cannot start with a digit.

Cannot be a Python keyword (like if, else, while, for, etc.).

Are case-sensitive (age, Age, and AGE are three different variables).

Conventions (PEP 8 - Python's Style Guide):
Use descriptive names: user_name is better than un, number_of_students is better than nos.

Use lowercase letters.

Separate words with underscores for improved readability (this is called snake_case). E.g., first_name, total_amount_calculated.

Avoid using single characters like l (lowercase L), O (uppercase o), or I (uppercase i) as they can look like numbers 1 and 0.

Constants (variables you plan never to change) are usually written in all uppercase letters with underscores: PI = 3.14, MAX_CONNECTIONS = 100.

Good Examples: player_health, transaction_id, is_logged_in
Bad Examples: ph, trId, loggedIn (uses camelCase, not snake_case)

Adopting these practices from day one will make your code look professional and make collaboration infinitely easier. To master these and other professional software development practices, consider enrolling in the comprehensive Python Programming course at codercrafter.in. Our curriculum is designed to take you from absolute beginner to job-ready developer.

Real-World Use Cases: Variables in Action
Variables aren't just academic concepts; they are the workhorses of every application.

User Input and Data Processing:

python

A simple program to calculate area of a circle

radius = float(input("Enter the radius of the circle: ")) # Store user input
PI = 3.14159 # Define a constant
area = PI * (radius ** 2) # Calculate and store the result
print(f"The area of the circle is: {area}") # Output the stored result
Managing Game State:

python

Variables to track a player's state in a game

player_name = "SirPython"
player_health = 100
player_inventory = ["sword", "shield", "potion"]
player_score = 0
is_game_over = False

Game logic would update these variables

player_health -= 10 # Player takes damage
player_score += 50 # Player gains points
player_inventory.append("magic amulet") # Player finds an item
Web Development (with a framework like Django or Flask):

python

In a Flask view function, variables are used to pass data to HTML templates

from flask import Flask, render_template

app = Flask(name)

@app.route('/user/')
def show_user_profile(username): # 'username' is a variable from the URL
user_bio = get_bio_from_database(username) # Store data from a database query
page_title = f"Profile of {username}" # Create a dynamic title
return render_template('profile.html', title=page_title, user=user_bio) # Pass variables to the template
This is just the tip of the iceberg. Every piece of data your program uses—from a simple username to a complex machine learning model—is held and manipulated using variables.

Frequently Asked Questions (FAQs)
Q1: How do I delete a variable?
You can use the del statement. This removes the reference to the object from the namespace.

python
x = 100
del x
print(x) # This will raise a NameError: name 'x' is not defined
Q2: What does "None" mean?
None is a special constant in Python that represents the absence of a value. It is its own data type (NoneType). It is often used to initialize a variable that you don't want to assign a specific value to yet.

python
result = None

... some code that might later assign a value to 'result' ...

Q3: Can a variable name have spaces?
No. Use underscores instead of spaces (first_name, not first name).

Q4: What's the difference between =, ==, and is?

= is the assignment operator. It assigns a value to a variable. x = 5

== is the equality operator. It checks if two values are equal. if x == 5:

is is the identity operator. It checks if two variables point to the exact same object in memory. This is different from == for mutable objects. if list_a is list_b:

Conclusion: Your Foundation is Set
Variables are the fundamental building blocks of Python programming. They are the containers that hold the data that gives your programs meaning and purpose. From simple strings and numbers to complex lists and custom objects, understanding how to create, name, and manipulate variables is the first giant leap on your coding journey.

We've covered a lot of ground—from basic declaration and dynamic typing to the more advanced concepts of scope and mutability. Remember the lunchbox analogy, follow the PEP 8 naming conventions, and always be mindful of your variable's scope.

Practice is key. Open your editor and start playing with variables. Break things, fix them, and experiment. The concepts will quickly become second nature.

If you found this deep dive helpful and are serious about transforming your curiosity into a career, this is just the beginning. To learn professional software development courses such as Python Programming, Full Stack Development, and MERN Stack, visit and enroll today at codercrafter.in.

Top comments (0)