python - How to pass local variables from one function into another? -
i trying make text-based game having troubles passing variables 1 function another. figured out how modify variable inside function , return new values overwrite original.
what need how room1()
, room2()
variables something1(x)
, something2(y)
, main()
unlock if
statement.
should have 2 different or 1 function something1(x)
, something2(y)
?
this general sample code problem i'm having:
def something1(x): x += 0 return x def something2(y): y += 0 return y def main(): print("1. try open door") print("2. go room1") print("3. go room2") choice = int(input("enter selection: ") if choice == "1": # trying if statement work variables # don't know function or parameters pass in order work if x == 3 , y == 2: print("you're free") else: print("you're not free") elif choice == "2": room1() elif choice == "3": room2() else: print("error") main() def room1(): print("1. push thing1") print("2. push thing2") print("3. push thing3") print("4. return previous room") pushchoice = input("enter selection: ") if pushchoice == "1": print("thing1 pushed") room1() elif pushchoice == "2": print("thing2 pushed") room1() elif pushchoice == "3": print("thing3 pushed") # modified variable x something1(x) x = 3 x = something1(x) room1() elif pushchoice == "4": main1() else: print("error") room1() def room2(): print("1. pull thinga") print("2. pull thingb") print("3. pull thingc") print("4. return previous room") pullchoice = input("enter selection: ") if pullchoice == "1": print("thinga pushed") room1() elif pullchoice == "2": print("thingb pushed") # modified variable y something2(y) y = 2 y = something1(y) room1() elif pullchoice == "3": print("thingc pushed") room1() elif pullchoice == "4": main1() else: print("error") room1()
you pass
variable 1 function returning variable. however, in order that, function has call function within function body, example:
def addandsquare(x, y): y = squarefunction(x+y) # sum x+y passed squarefunction, returns square , stores in y. return y def squarefunction(a): return (a*a) # returns square of given number print(addandsquare(2, 3)) # prints 25
however, if cannot call function within it's body, use local variable of function, can declare variable global both functions.
here example of that:
globvar = 0 def set_globvar_to_one(): global globvar # needed modify global copy of globvar globvar = 1 def print_globvar(): print globvar # no need global declaration read value of globvar set_globvar_to_one() print_globvar() # prints 1
hope helps!
Comments
Post a Comment