How to Call a Variable from Another Function in Python?

In this tutorial, I will show you how to call a variable from another function in Python using different methods and examples. This is a bit tricky, and I hope all these examples will be helpful.

To call a variable from another function in Python using the global variable method, you declare the variable outside of any function, making it accessible throughout the program. Within each function that needs to access or modify this variable, you use the global keyword followed by the variable name. Here is an example:

# Declare a global variable
visitors = 0

def new_visitor():
    global visitors
    visitors += 1
    print(f"New visitor added. Total visitors: {visitors}")

def display_visitors():
    global visitors
    print(f"Total visitors: {visitors}")

# Simulate new visitors
new_visitor()  # Output: New visitor added. Total visitors: 1
new_visitor()  # Output: New visitor added. Total visitors: 2
display_visitors()  # Output: Total visitors: 2

By using the global keyword, both new_visitor and display_visitors functions can access and modify the visitors variable, ensuring consistent tracking of the visitor count across the application.

Call a Variable from Another Function in Python

Now, let me show you how to call a variable from another function in Python using different methods.

1. Using Global Variables

Global variables are accessible throughout the entire program, which means any function can read and modify them. This is one of the simplest ways to share variables between functions.

Let me show you an example.

Example:

# Example: Tracking the number of visitors to a website

# Declare a global variable
visitors = 0

def new_visitor():
    global visitors
    visitors += 1
    print(f"New visitor added. Total visitors: {visitors}")

def display_visitors():
    global visitors
    print(f"Total visitors: {visitors}")

# Simulate new visitors
new_visitor()  # Output: New visitor added. Total visitors: 1
new_visitor()  # Output: New visitor added. Total visitors: 2
display_visitors()  # Output: Total visitors: 2

In this example, the visitors variable is declared globally. Both new_visitor and display_visitors functions can access and modify this variable.

I executed the above Python code and you can see the exact output in the screenshot below:

how to call a variable from another function in python

Check out How to Check if a Global Variable is Defined in Python?

2. Using Function Parameters and Return Values

Another method is to pass variables as parameters to functions and return values from functions in Python. This method limits the scope of variables and avoids potential issues with global variables.

Let me show you an example.

Example:

# Example: Calculating the total sales in different states

def calculate_sales(state, sales):
    # Assume some complex calculation here
    total_sales = sum(sales)
    return total_sales

def display_sales(state, total_sales):
    print(f"Total sales in {state}: ${total_sales}")

# Sales data for California
california_sales = [1200, 3400, 5600]
total_california_sales = calculate_sales("California", california_sales)
display_sales("California", total_california_sales)  # Output: Total sales in California: $10200

In this example, the calculate_sales function calculates the total sales and returns the value, which is then passed to the display_sales function.

Here is the output in the screenshot below:

call a variable from another function in python

Read Python Function Examples with Parameters

3. Using Classes and Instances

Using classes and instances is a more structured way to manage variables and functions in Python. This approach is particularly useful for larger applications.

Here is another example.

Example:

# Example: Managing a library system

class Library:
    def __init__(self):
        self.books = []

    def add_book(self, book):
        self.books.append(book)
        print(f"Book '{book}' added to the library.")

    def list_books(self):
        print("Books in the library:")
        for book in self.books:
            print(f"- {book}")

# Create a library instance
my_library = Library()

# Add books to the library
my_library.add_book("To Kill a Mockingbird")  # Output: Book 'To Kill a Mockingbird' added to the library.
my_library.add_book("1984")  # Output: Book '1984' added to the library.

# List all books
my_library.list_books()
# Output:
# Books in the library:
# - To Kill a Mockingbird
# - 1984

In this example, the Library class manages the list of books. Methods add_book and list_books can access and modify the books attribute.

Read How to Check if a Global Variable is Initialized in Python?

4. Using Closures

Closures allow you to capture and store the state of variables within a function, which inner functions can then use in Python.

Here is an example.

Example:

# Example: Tracking donations for a charity event

def charity_event():
    total_donations = 0

    def add_donation(amount):
        nonlocal total_donations
        total_donations += amount
        print(f"Donation added: ${amount}. Total donations: ${total_donations}")

    def get_total_donations():
        return total_donations

    return add_donation, get_total_donations

# Create a charity event
add_donation, get_total_donations = charity_event()

# Add donations
add_donation(100)  # Output: Donation added: $100. Total donations: $100
add_donation(250)  # Output: Donation added: $250. Total donations: $350

# Get total donations
print(f"Total donations: ${get_total_donations()}")  # Output: Total donations: $350

In this example, the charity_event function creates a closure that captures the total_donations variable. The inner functions add_donation and get_total_donations can access and modify this variable.

Here is the output in the screenshot below:

python call a variable from another function

Conclusion

In this tutorial, I have explained how to call a variable from another function in Python using different methods like using global variables, function parameters, classes, or closures, etc.

If you still have any questions feel free to leave a comment below.

You may also like the following tutorials:

Leave a Comment