scope - Holding an experience variable to be read/written to throughout a program (python 3) -
scope - Holding an experience variable to be read/written to throughout a program (python 3) -
i've been stuck trying way have experience variable in "game" trying work. have found out able import different python files i've created, makes much neater files instead of having in 1 file. think i'm having problem figuring out how global variables work though. if can give me solution without using external module, or creating separate file great. variables remain within .py files.
here's thought work. maybe work, don't know how correctly. want there 3 (or more) files. file 1 main file. have main menu , allow player go other events. file 2 contain variable player_experience , equal 0 (but added on throughout game). file 3+ events can done , in return, give experience. need experience variable able read throughout files, , can added onto whenever needed.
thought using "global player_experience" @ top of files create work, not able work.if makes difference, using definitions in files. example:
#file1.py print('what want do? 1 - game, 2 - check experience') donow = input() if donow == '1': game() if donow == '2': check_experience() #just pretend defined somewhere
the check_experience function print out player's experience. function able used throughout files. (which think can defining function in file, , importing funciton whenever need it)
#file2.py print('yay beat game, here's 500 experience') player_experience += 500 print('you have',player_experience,'experience.')
i'm sorry if mutual question, have tried own research on this, wasn't able find without creating separate configuration-type file, bit beyond abilities @ moment. appreciate help given me, if there can create "better" question, please tell me.
you need import minigame function , utilize update experience variable that'll global in main file.
/main.py
from minigame import game exp = 0 exp += game() print(exp)
/minigame.py
def game(): '''this function can not reference `exp`. if `exp` defined in module, it'd different `exp` in different namespace.''' score = 0 ... homecoming score
python scope
Comments
Post a Comment