Python Using variable from one function in another

3031 views python
3

In one function I get three pieces of information and write them to a text file. In another function I write over one of the pieces of information (Code).

The variables (FirstName, SecondName, Code) from function 1 are not known by function 2 - how do I solve this? / Pass them from one function to another?

def function1():

FirstName = input("Enter First Name")
SecondName = input("Enter Surname")
Code = input("Enter Code")

AllDetails = (GuestFirstName, GuestSecondName, Code)
f = open("AllDetails.txt","w") 
f.write(str(AllDetails))    
f.close()

menu()

def function2():

Newcode = input ("Enter if new code needed")
if Newcode == "Y":
    Code = "****"
    AllDetails = (FirstName, SecondName, Code)
    f = open("AllDetails.txt","w") 
    f.write(str(AllDetails))
    f.close()

menu() 

answered question

1 Answer

2

How about return the values of the function and assign them to variables like this

def function1():
    FirstName = input("Enter First Name")
    SecondName = input("Enter Surname")
    Code = input("Enter Code")
    return FirstName, SecondName, Code

Then you can assign them and use them in the rest of your code

FirstName, SecondName, Code = fucntion1()

posted this

Have an answer?

JD

Please login first before posting an answer.