1

I am creating a game with Python and the Pygame module and I was wondering if there was a way to call a function based on the value of a variable.

I have a variable called 'levels' and to switch the levels, for now I am using an if statement finding the value of the variable and executing the corresponding function. It looks something like this :

if levels == 1:
    level1()
if levels == 2:
    level2()

etc

Is there a way to execute the function based on the value of the variable?

I know you can combine it to form a string so maybe call a function based on the value of the string?

Something like :

str = 'level'+str(levels)
# call the value of str as a function
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    The "variable variables" dupe isn't a useful one IMO unless you've already internalized the concept that function names are variables (which is usually not obvious to beginners). I suggest using a dict to map level identifiers to level functions: `{1: level1, 2: level2}[levels]()` Define the dict in a single place, and then the rest of your code can access a level by providing the level ID and getting the corresponding function. – Samwise Mar 31 '22 at 17:07
  • thats smart ill try that out. So far, I've gotten it to work with the if statements using a slightly different structure than what I initially thought of when posting this question. I don't have much experience with dictionaries so will have to look at some documentation but it should work. Thanks! – FieryFalcon Apr 01 '22 at 10:03

0 Answers0