How to share variable value between function

How to share variable value between function

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

def xyz():
   b=10
   


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

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

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
2 Likes

Thank you :heavy_heart_exclamation:

1 Like

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

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()
2 Likes

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

Let your functions return something

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

def xyz():
   return 10

a = abc()
b = xyz()

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

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

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:

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:

# nc.set_valid_input(7)
2 Likes

Please, its not 1973 when Wulf and Shaw first wrote their classic paper Global Variables Considered Harmful. Let’s not encourage poor habits 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:

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

def xyz():
    b = 10
    return b


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

2 Likes

You could submit a request to have that caveat inserted into the official Python documentation on the global statement.

1 Like

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:

 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.

1 Like

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

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 ()   '''

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.

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()
1 Like

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!

1 Like

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

1 Like

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.

1 Like

Ok
Thank you for your guidence

1 Like