Open In App

How to Use a Variable from Another Function in Python

Last Updated : 31 May, 2024
Summarize
Comments
Improve
Suggest changes
Share
2 Likes
Like
Report

Using a variable from another function is important for maintaining data consistency and code reusability. In this article, we will explore three different approaches to using a variable from another function in Python.

Use a Variable from Another Function in Python

Below are the possible approaches to using a variable from another function in Python.

  • Using Global Variables
  • Using Function Parameters
  • Using Class Attributes

Use a Variable from Another Function Using Global Variables

In this example, we are using global variables to share a variable between functions. First, we declare the variable as global within one function to set its value, and then we access it using global in another function to use its value.


Output
Hello from GeeksforGeeks

Use a Variable from Another Function Using Function Parameters

In this example, we pass the variable as a parameter to another function. This approach makes sure that the function can access the variable's value without relying on global variables.


Output
Hello from GeeksforGeeks

Use a Variable from Another Function Using Class Attributes

In this example, we use a class to encapsulate the variable as an attribute. This allows different methods within the class to access and modify the variable's value, providing a structured approach to sharing variables between functions.


Output
Hello from GeeksforGeeks

Next Article
Article Tags :
Practice Tags :

Similar Reads