# How to share variable value between function

**URL:** <https://discuss.python.org/t/how-to-share-variable-value-between-function/21402>\
**Category:** Python Help\
**Tags:** help\
**Created:** [November 25, 2022, 11:45am UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402 "2022-11-25T11:45:50Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![Anurag.kumar](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@Anurag.kumar](https://discuss.python.org/u/Anurag.kumar)\
**Post date:** [November 25, 2022, 11:45am UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/1 "2022-11-25T11:45:50Z")

</div>

How to share variable value between function

```auto
def abc():
   a=int(input("enter here:"))

def xyz():
   b=10
   

if a==b:
 print ('working')

```

---

<div class="post-metadata">

**Author:** ![Quercus](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/quercus/32/31483_2.png) [@Quercus](https://discuss.python.org/u/Quercus)\
**Post date:** [November 25, 2022, 12:55pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/2 "2022-11-25T12:55:11Z")

</div>

You might want to declare the shared variables as `global`, as in the following:

```auto
def abc():
    global a
    a=int(input("enter here:"))

def xyz():
    global b
    b=10
   
abc()
xyz()
if a==b:
    print ('working')

```

Input and output:

```
enter here:10
working

```

---

<div class="post-metadata">

**Author:** ![Anurag.kumar](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@Anurag.kumar](https://discuss.python.org/u/Anurag.kumar)\
**Post date:** [November 25, 2022, 1:11pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/3 "2022-11-25T13:11:35Z")

</div>

Thank you ❣

---

<div class="post-metadata">

**Author:** ![Quercus](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/quercus/32/31483_2.png) [@Quercus](https://discuss.python.org/u/Quercus)\
**Post date:** [November 25, 2022, 1:24pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/4 "2022-11-25T13:24:42Z")

</div>

You could also consider defining a `class`, as follows, instead of using `global` variables:

```auto
class NumberChecker:
    def __init__ (self, valid=10):
        self.valid = valid
    def set_valid_input(self, valid=10):
        self.valid = valid
    def get_and_check_user_input(self):
        self.user_input = int(input("Enter number: "))
        if self.user_input == self.valid:
            print("You got it!")
            return True
        else:
            print("Sorry!")
            return False
   
nc = NumberChecker(9)
# nc.set_valid_input(7)
nc.get_and_check_user_input()

```

---

<div class="post-metadata">

**Author:** ![gkb](https://avatars.discourse-cdn.com/v4/letter/g/6f9a4e/32.png) [@gkb](https://discuss.python.org/u/gkb)\
**Post date:** [November 25, 2022, 2:03pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/5 "2022-11-25T14:03:24Z")

</div>

One more way, which for me seems to be the most straightforward one:

Let your functions return something

```python
def abc():
   return int(input("enter here:"))

def xyz():
   return 10

a = abc()
b = xyz()

if a == b:
   print("working")

```

---

<div class="post-metadata">

**Author:** ![Quercus](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/quercus/32/31483_2.png) [@Quercus](https://discuss.python.org/u/Quercus)\
**Post date:** [November 25, 2022, 5:13pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/6 "2022-11-25T17:13:03Z")

</div>

You have the option of looping until the user enters the correct input. Using @gkb’s functions, you could do this:

```auto
while abc() != x:
   abc()

print("Got it!")

```

Example input and output:

```
enter here:7
enter here:12
enter here:10
Got it!

```

With the `class NumberChecker` example given prior to that, you could do this:

```auto
nc = NumberChecker(9)
# nc.set_valid_input(7)
while not nc.get_and_check_user_input():
    print("Keep trying ...")

```

Example input and output:

```
Enter number: 7
Sorry!
Keep trying ...
Enter number: 12
Sorry!
Keep trying ...
Enter number: 9
You got it!

```

Note that this line can be uncommented, so that it executes:

```auto
# nc.set_valid_input(7)

```

---

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [November 25, 2022, 1:07am UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/7 "2022-11-25T01:07:33Z")

</div>

> [@](#):
>
> You might want to declare the shared variables as `global`, as in the following:

Please, its not 1973 when Wulf and Shaw first wrote their classic paper _Global Variables Considered Harmful_. Let’s not encourage [poor habits](https://embeddedartistry.com/fieldatlas/the-problems-with-global-variables/) that the beginner will just have to unlearn.

Global variables are not the answer, unless the question is “How do I write bad code that will give me problems later on?”

This is better:

```python
def abc():
    a = int(input("enter here:"))
    return a

def xyz():
    b = 10
    return b

a = abc()
b = xyz()
if a == b:
    print ('working')

```

---

<div class="post-metadata">

**Author:** ![Quercus](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/quercus/32/31483_2.png) [@Quercus](https://discuss.python.org/u/Quercus)\
**Post date:** [November 26, 2022, 12:31pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/8 "2022-11-26T12:31:30Z")

</div>

> [@steven.daprano](#):
>
> Global variables are not the answer, unless the question is “How do I write bad code that will give me problems later on?”

You could submit a request to have that caveat inserted into the official Python documentation on [the global statement](https://docs.python.org/3/reference/simple_stmts.html#global).

---

<div class="post-metadata">

**Author:** ![Stockfish](https://avatars.discourse-cdn.com/v4/letter/s/eb9ed0/32.png) [@Stockfish](https://discuss.python.org/u/Stockfish)\
**Post date:** [November 26, 2022, 12:53pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/9 "2022-11-26T12:53:39Z")

</div>

As far as I know once you “return” your variable no more code will be read in the function; and sometimes functions can be very complicated. If you somehow have to write complicated functions, you might want to try this:

```auto
 K = []
 L = []

 
 def abc():
     a = int(input("enter here:"))
     K.append(a)
 
 
 def xyz():
     b = 10
     L.append(b)
 
 
 abc()
 xyz()
 
 if K == L:
     print('working')

```

This way, you can keep coding inside your functions.

---

<div class="post-metadata">

**Author:** ![Anurag.kumar](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@Anurag.kumar](https://discuss.python.org/u/Anurag.kumar)\
**Post date:** [November 28, 2022, 3:30am UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/10 "2022-11-28T03:30:27Z")

</div>

Thank you everyone  
Here’s the final result  
Feel free to modify and add your own code

```auto
x=0
def select ():
    print('''
————————————————————————————
1) login
2) signin       
3) exit            
————————————————————————————
''')
    a=int(input('enter here: '))
    
    if a==1:
     log()
    if a==2:
     sig()
    if a==3:
     print('exiting...')
        
    else:
     print('invalid input')
     select ()

def sig():
    
    global s
    s=input ('enter name: ')
    global t
    t=input ('enter password : ')
    global x
    x+=1
    use()
      
def log():
    if x==1:     
     i=5
     while i>0:
      c=input ('renter name: ')
      d=input ('renter password : ')
    
      if c==s and d==t:
       use()
      else:
       print('wrong username and password ')
       i-=1
      if i==0:
       print('too many times entered wrong username or password')
       select()
    if x==0:
     print('you are not signed in ')
     select ()
    

def use():
    print('''
hello''')
    print('''
————————————————————————————
1) mail
2) logout 
————————————————————————————
''')
    z=int(input('enter here: '))
    if z==1:
     print('no mail received ')
     use()
    if z==2:
     select ()
    else:
     print('invalid input ')
     use()

select () '''
```

---

<div class="post-metadata">

**Author:** ![Quercus](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/quercus/32/31483_2.png) [@Quercus](https://discuss.python.org/u/Quercus)\
**Post date:** [November 28, 2022, 8:50am UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/11 "2022-11-28T08:50:55Z")

</div>

In your code, you should use meaningful names for variables, such as `username` and `password` instead of `a` and `b`.

The title of your post suggests that you would like to share variables between functions. Have you learned, yet, about defining and instantiating classes? Within a class, you can define methods, which are functions that can easily share variables. Below is some code that defines and instantiates a class named `User`. If that is too advanced to understand at this point, you can learn about that topic at a later time.

For now, you can revise your code to share values between the functions by passing them to those functions as arguments instead of declaring them as `global`.

```auto
import random
class User:
    def __init__ (self, username="guest", password="abc"):
        self.username = username
        self.password = password
        self.logged_in = False
    def set_username(self, username):
        self.username = username
    def set_password(self, password):
        self.password = password
    def signup(self):
        print("Signing up ...")
        self.set_username(input("Choose a username: "))
        self.set_password(input("Choose a password: "))
    def login(self):
        print("Please log in ...")
        uname = input("Username: ")
        passwd = input("Password: ")
        if uname == self.username and passwd == self.password:
            print(f"Hello, {self.username}.")
            self.logged_in = True
            self.session()
        else:
            print("Invalid username of password.")
    def logout(self):
        print("Bye.")
        self.logged_in = False
        
    def session(self):
        while self.logged_in:
            print("1) play game")
            print("2) logout")
            choice = input("Enter choice: ")
            if choice == "1":
                play_game()
            if choice == "2":
                self.logout()

def play_game():
    num = random.randint(1, 10)
    for i in range(3):
        guess = int(input("Guess number (1 - 10): "))
        if guess == num:
            print("You got it!")
            break
        else:
            print("Sorry.")
    else:
        print("Game over.")
        
user = User()
user.signup()
user.login()

```

---

<div class="post-metadata">

**Author:** ![Geomorphicmat](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/geomorphicmat/32/9928_2.png) [@Geomorphicmat](https://discuss.python.org/u/Geomorphicmat)\
**Post date:** [November 28, 2022, 10:23am UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/12 "2022-11-28T10:23:42Z")

</div>

It’s something that I love about Python is that there are so many ways to execute the same logic or request!  
There are some reasons why the script needs to be more complex such as the use of class and global variables (please don’t ask me why)…and ways to simpliPy the script.  
This topic is a great example of this. Thanks. I’m always learning something!

---

<div class="post-metadata">

**Author:** ![Anurag.kumar](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@Anurag.kumar](https://discuss.python.org/u/Anurag.kumar)\
**Post date:** [November 28, 2022, 11:55am UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/13 "2022-11-28T11:55:31Z")

</div>

I am learning about class  
Global function was easy to understand so I used it in this program but I will improve it later as I will learn new stuff

---

<div class="post-metadata">

**Author:** ![Quercus](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/quercus/32/31483_2.png) [@Quercus](https://discuss.python.org/u/Quercus)\
**Post date:** [November 28, 2022, 12:53pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/14 "2022-11-28T12:53:03Z")

</div>

> [@Anurag.kumar](#):
>
> I am learning about class

Is this part of a course that you are taking? If so, then hopefully the next step will be to learn how to revise the code to reorganize the `global` variables and functions into instance variables and methods. That could be a great educational exercise.

---

<div class="post-metadata">

**Author:** ![Anurag.kumar](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@Anurag.kumar](https://discuss.python.org/u/Anurag.kumar)\
**Post date:** [November 28, 2022, 1:28pm UTC](https://discuss.python.org/t/how-to-share-variable-value-between-function/21402/15 "2022-11-28T13:28:15Z")

</div>

Ok  
Thank you for your guidence
