View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Mastering Python Variables: Complete Guide with Examples

Updated on 15/05/20252,192 Views

When you start learning Python, one of the first concepts you'll come across is python variables. Think of a variable as a labeled storage box for your data. Whether you're storing a user's name, the result of a calculation, or even a complex dataset, python variables help you keep that information handy and organized. 

But here's the thing — python variables are more than just containers. They’re dynamic, flexible, and incredibly easy to use, which is one of the many reasons Python is loved by beginners and pros alike. Also, it’s a must to learn concept to become a pro level python developer

In this blog, we’ll walk through everything you need to know about python variables, including what they are, how they work, how to use them effectively, and some of the neat tricks you can do with them. Whether you’re just getting started or brushing up your skills, this guide will make sure you’ve got a solid grip on the foundation of working with python variable types. Also, it’ll help you go through any of the next-gen software development course

What are Python Variables?

At its core, a python variable is simply a name that refers to a value. When you assign a value to a python variable, Python creates an object in memory and binds that name to the object. This makes working with data seamless and intuitive.

In addition, also know about the advantages of Python to strengthen your foundational knowledge. 

How Python Variables Work

In Python, you don’t need to declare the type of a variable. Just assign a value and Python figures it out for you based on the data.

Here's a basic example:

# Assigning a string value to a python variable
name = "Alice"

# Assigning an integer to another python variable
age = 30

# Assigning a floating-point number
height = 5.6

# Output the variables
print(name)    # Output: Alice
print(age)     # Output: 30
print(height)  # Output: 5.6

Explanation:

In this example, we’ve created three python variables: `name`, `age`, and `height`. Each one is storing a different type of value — a string, an integer, and a float respectively. Python automatically identifies the type based on the assigned value.

Consistently Advance Your Career with the following Full-stack Development Courses: 

Types of Python Variables (Based on Data Type)

While python variables are dynamically typed, the data they hold can be categorized into several standard types. Here are some of the most commonly used variable types:

Type

Description

Example

str

Stores text data (strings)

"Hello, World!"

int

Stores whole numbers

42

float

Stores decimal numbers

3.14

bool

Stores boolean values (True or False)

True, False

list

Ordered, changeable collection of items

[1, 2, 3, "apple"]

tuple

Ordered, unchangeable collection of items

(10, 20, 30)

dict

Stores data in key-value pairs

{"name": "Alice", "age": 30}

set

Unordered collection of unique items

{1, 2, 3}

For more in-depth details, explore our article on Data Types in Python

Rules for Naming Python Variables

Following rules must be followed by using python variables in your programs: 

  • Must start with a letter (a-z, A-Z) or an underscore (_); cannot start with a digit.
  • Can contain only letters, digits, and underscores; special characters like @, %, and - are not allowed.
  • Variable names are case-sensitive; name, Name, and NAME are distinct.
  • Cannot use Python reserved keywords like class, if, for, return, etc., as variable names.
  • Use descriptive names to improve readability, like user_age instead of vague names like ua.

Also read our article on Operators in Python fore more detailed understanding. 

Assigning Values to Python Variables

In Python, assigning values to python variables is simple. You use the `=` operator, and Python automatically identifies the type of the variable based on the assigned value.

Basic Assignment

# Assigning different types of values to python variables
name = "Alice"       # string
age = 25             # integer
height = 5.7         # float
is_student = True    # boolean

print(name)       
print(age)         
print(height)      
print(is_student)  

Output:

Alice

25

5.7

True

Explanation:

Each python variable holds a different type of data. Python automatically detects the data type based on the value.

Reassigning Values

You can reassign a new value (even of a different type) to a python variable.

# Reassigning a python variable to a new value and type
count = 10         # Initially an integer
count = "Ten"      # Now a string
print(count)    

Output:

Ten

Explanation:

The python variable `count` was initially an integer but was reassigned to a string. Python allows such reassignment without issues.

Explore Python Frameworks article to gain advance-level insights. 

Assigning the Same Value to Multiple Variables

You can assign the same value to multiple python variables in one line.

# Assigning the same value to multiple python variables
x = y = z = 100

# Output the values of each variable
print(x)  
print(y)  
print(z)  

Output:

100

100

100

Explanation:

In this case, the value `100` is assigned to three different python variables (`x`, `y`, and `z`) in a single line.

Python Variables Multiple Assignments

In Python, you can assign multiple variables in a single line, either with the same or different values. This can help make your code cleaner and more concise.

Assigning Different Values to Multiple Variables

You can assign different values to multiple python variables on the same line, using a comma to separate the variable names and values.

# Assigning different values to multiple python variables
a, b, c = 10, 20, 30

# Output the assigned values
print(a)  # Output: 10
print(b)  # Output: 20
print(c)  # Output: 30

Output:

10

20

30

Explanation:

In this example, the values `10`, `20`, and `30` are assigned to the variables `a`, `b`, and `c` respectively in a single line.

Assigning the Same Value to Multiple Variables

You can also assign the same value to multiple python variables in a single line.

# Assigning the same value to multiple python variables
x = y = z = 50

# Output the assigned values
print(x)  # Output: 50
print(y)  # Output: 50
print(z)  # Output: 50

Output:

50

50

50

Explanation:

Here, the value `50` is assigned to three different variables (`x`, `y`, and `z`) in a single line.

Swap Values Between Variables

Python allows you to swap the values of two variables without needing a temporary variable.

# Swapping values between two python variables
a, b = 10, 20
a, b = b, a  # Swapping values

# Output the swapped values
print(a)  # Output: 20
print(b)  # Output: 10

Output:

20

10

Explanation:

The values of `a` and `b` are swapped in one line using Python's built-in tuple unpacking feature.

Type Casting of Python Variables

In Python, type casting refers to the conversion of a python variable from one data type to another. This is especially useful when you need to perform operations between different types of data or handle user inputs.

Implicit Type Casting (Automatic Type Conversion)

Python automatically converts smaller data types to larger ones when required. This is known as implicit type casting.

# Implicit type casting example
a = 5       # Integer
b = 3.2     # Float
result = a + b  # Python automatically converts 'a' to float before performing the operation

print(result)  

Output:

8.2

Explanation:

In this example, Python automatically converts the integer `a` into a float to perform the addition with the float `b`.

Explicit Type Casting (Manual Conversion)

Sometimes, you may want to manually convert a variable from one type to another. This is called explicit type casting, which is done using the built-in functions such as `int()`, `float()`, `str()`, etc.

# Explicit type casting examples
x = "123"        # String
y = int(x)       # Converting string to integer
z = float(y)     # Converting integer to float

print(y)  
print(z)  

Output:

123

123.0

Explanation:

Here, the string `x` is first converted to an integer using `int()`, and then the integer is converted to a float using `float()`.

Converting User Input

When you receive user input, it’s always in the form of a string. You often need to convert it to other types like integers or floats.

# Taking user input and converting it
user_input = input("Enter a number: ")  # Input is always a string
num = int(user_input)  # Converting the string to an integer

# Output the converted value
print(num)

Example Output:

Enter a number: 42

42

Explanation:

The `input()` function returns a string, and we convert it to an integer using `int()` before performing any operations on it.

Getting the Type of a Python Variable

In Python, it’s often useful to check the type of a python variable to ensure it holds the expected value type. Python provides the built-in `type()` function for this purpose, which returns the class type of the variable.

Using `type()` to Check a Variable’s Type

You can use the `type()` function to determine the type of any python variable. It helps in debugging and understanding your data.

# Checking the type of different python variables
name = "Alice"      # string
age = 25            # integer
height = 5.7        # float
is_active = True    # boolean

# Output the types
print(type(name))     
print(type(age))       
print(type(height))    
print(type(is_active)) 

Output:

<class 'str'>

<class 'int'>

<class 'float'>

<class 'bool'>

Explanation:

The `type()` function is used to print the class type of each python variable. For example, `name` is a string, `age` is an integer, etc.

In addition, explore article on slicing in Python to do more with string data type in your applications. 

Checking Types Before Operations

It’s a good practice to check variable types before performing certain operations, especially if you're working with user inputs or dynamic data.

# Checking the type before performing arithmetic operation
x = 10        # Integer
y = "5"       # String

# Check types before adding
if isinstance(y, int):
    result = x + y
else:
    print("Cannot add integer and string!")

Output:

Cannot add integer and string!

Explanation:

In this example, we used `isinstance()` to ensure that `y` is an integer before trying to add it to `x`. Since `y` is a string, the addition operation is prevented.

Scope of Python Variables: Local and Global

In Python, the scope of a variable defines where it can be accessed in your code. The two most important types of scope are local and global.

Local Scope

A python variable has a local scope if it is defined within a function. This means that the variable is only accessible inside that function.

def my_function():
    local_var = "I am local"  # Local variable
    print(local_var)  # Accessible inside the function

my_function()

Output:

I am local

Explanation:

In this example, `local_var` is defined inside `my_function()`. It is accessible only within the function and cannot be used outside of it.

Global Scope

A python variable has a global scope if it is defined outside any function. A global variable is accessible throughout the entire script or module, including inside functions. For more details, read about our article on global variable in Python

global_var = "I am global"  # Global variable

def my_function():
    print(global_var)  # Accessible inside the function

my_function()

Output:

I am global

Explanation:

In this case, `global_var` is defined outside the function and is accessible both inside and outside the function, as it has global scope.

Object Reference in Python Variables

In Python, variables don’t store data directly. Instead, they store references to objects in memory. This means when you assign a variable to another, both variables refer to the same object in memory. This is important to understand when working with mutable and immutable objects.

Also, it’s recommended to learn about memory management in Python for better understanding. 

Object References in Python

When a python variable is assigned a value, it doesn't directly store the value. Instead, it stores a reference to the object that contains the value.

a = [1, 2, 3]  # List assignment
b = a          # b refers to the same object as a

# Modify the object using b
b.append(4)

print(a) 
print(b) 

Output:

 [1, 2, 3, 4]

[1, 2, 3, 4]

Explanation:

In this example, `a` and `b` both refer to the same list in memory. When the list is modified through `b`, the change is reflected in `a` as well. This happens because both variables are referencing the same object.

Mutable vs Immutable Objects

Python objects can be either mutable (can be changed after creation) or immutable (cannot be changed after creation). Lists are mutable, while strings are immutable.

Mutable Objects (e.g., List)

When working with mutable objects, both variables that refer to the same object will be affected by changes made to the object.

x = [10, 20, 30]  # Mutable object (list)
y = x             # y refers to the same object as x

x.append(40)      # Modify the list through x

print(x)  
print(y)  

Output:

 [10, 20, 30, 40]

[10, 20, 30, 40]

Explanation:

Both `x` and `y` refer to the same list object. When the list is modified via `x`, the change is reflected in `y`.

Immutable Objects (e.g., String)

For immutable objects, modifying one variable will not affect the other, because a new object is created instead of modifying the original object.

a = "hello"   # Immutable object (string)
b = a         # b refers to the same object as a

a = "world"   # Reassign a to a new string object

print(a) 
print(b) 

Output:

world

hello

Explanation:

Strings are immutable. When `a` is reassigned to a new string, `b` remains unchanged, as it still refers to the original string `"hello"`.

Delete a Python Variable Using `del` Keyword

In Python, variables can be deleted using the `del` keyword. This keyword removes a variable or an object from memory, making it inaccessible for further use. It is useful when you want to clean up memory or remove references to objects that are no longer needed.

Deleting a Single Variable

You can delete a single python variable by using the `del` keyword followed by the variable name.

x = 10  # Assigning a value to a variable

del x  # Deleting the variable

# Trying to access x after deletion will raise an error
# print(x)  # This will raise a NameError: name 'x' is not defined

Explanation: 

The `del` keyword deletes the variable `x` from memory. After deletion, if you attempt to access `x`, Python will raise a `NameError` because the variable no longer exists.

Also read about list methods in Python to gain pro-level development insights. 

Deleting an Element from a List

You can also use `del` to remove an element from a list by specifying its index.

my_list = [1, 2, 3, 4, 5]

# Deleting the element at index 2 (the number 3)
del my_list[2]

print(my_list) 

Output:

 [1, 2, 4, 5]

Explanation:

In this case, `del` removes the element at index 2 of `my_list` (the value `3`), and the list is updated accordingly.

Deleting Multiple Variables

You can also delete multiple variables at once by passing them as a comma-separated list.

a = 10
b = 20
c = 30

# Deleting multiple variables
del a, b, c

# Trying to access any of these variables will raise an error
# print(a)  # This will raise a NameError

Explanation:

The `del` statement deletes multiple variables at once. After deletion, attempting to access any of the deleted variables will result in a `NameError` since they are no longer defined.

Explore our must read article on Speech recognition in Python develop cutting-edge application. 

Conclusion

Python variables are key to understanding how data is stored and manipulated within your programs. Whether dealing with local or global scopes, knowing where and how variables are accessible is crucial for managing the flow of your code. Additionally, understanding the concept of object references helps you grasp the behavior of mutable and immutable objects and how changes to one variable can affect others. By leveraging Python’s del keyword, you can clean up your code by deleting variables and freeing up memory when they are no longer needed.

In summary, mastering Python variables allows you to write cleaner, more efficient code. By knowing when and how to use type casting, handle variable scopes, and delete unused variables, you can improve the maintainability and performance of your Python applications. As you continue coding, these foundational concepts will help you create more organized and bug-free programs.

FAQs

1. How do Python variables work under the hood?

Python variables don’t directly store values. Instead, they are labels attached to objects in memory. When a variable is created, Python automatically manages the memory allocation and garbage collection. Variables are names pointing to memory locations where objects are stored, and Python's memory management handles the object's lifecycle.

2. Why do Python variables not require type declarations?

Python is a dynamically typed language, meaning the type of a variable is determined at runtime, not in advance. This allows for more flexibility in coding since you can change the type of a variable on the fly. It also reduces verbosity in code, making it easier to work with for beginners and experts alike.

3. What happens if two variables reference the same object?

If two variables reference the same object, modifying the object through one variable will affect the other. This is because they both point to the same memory location. This concept is especially important when dealing with mutable data types like lists and dictionaries, where changes to one will reflect in the other.

4. Can I use a Python variable before assigning it a value?

No, Python requires that a variable must be assigned a value before being used. Attempting to access a variable that hasn’t been assigned will result in a NameError. This is one of Python’s safety features to prevent bugs caused by referencing undefined variables.

5. Can variables be assigned based on conditions in Python?

Yes, Python allows variables to be assigned values based on conditions using conditional expressions. For instance, the ternary operator x = 10 if y > 5 else 20 will assign 10 to x if y is greater than 5, otherwise 20. This provides a concise way to conditionally set variable values.

6. Are Python variables case-sensitive?

Yes, Python variables are case-sensitive, meaning myVariable, MyVariable, and MYVARIABLE are all treated as distinct variables. This is important to remember when naming variables, as accidental case differences could lead to bugs or unexpected behavior in your program.

7. What is the difference between Python variables and constants?

Python doesn’t have built-in constant variables like other languages. However, you can conventionally indicate constants by using all uppercase letters for variable names (e.g., PI = 3.14). Although Python won’t prevent you from changing these values, it's a widely accepted practice to treat such variables as immutable.

8. How does Python handle variables with large data?

When working with large data (e.g., large lists or dictionaries), Python uses references rather than copying the data for each variable. This saves memory and improves performance since large objects are not duplicated in memory. However, this can also lead to unexpected changes if multiple variables are pointing to the same object.

9. What is the role of the global keyword in Python?

The global keyword allows you to modify a global variable inside a function. Without it, any assignment to a variable within a function creates a local copy of the variable. The global keyword tells Python to refer to the global variable instead of creating a new local one.

10. Why do Python variables behave differently than in other languages?

Python variables behave differently because Python is a high-level, dynamically typed language. This contrasts with statically typed languages where variables are explicitly typed and checked at compile time. In Python, variables simply point to objects, and the interpreter handles memory management and type checking at runtime.

11. How can I check if a variable exists in Python?

You can check if a variable exists using a try-except block or the globals() function. Using globals() allows you to check the variable in the global scope. For example, if 'x' in globals(): checks if the variable x is defined. Alternatively, a try-except block can catch NameError.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.