I'm a Python newbie. I wrote this code, but heard that declaring global variables isn't a good practice. What would be in this case the right way to write this function?
index = 0
def level_selection():
global index
level = raw_input("Choose the desired level of difficulty: easy, medium or hard")
if level.lower() == "easy":
return level1
if level.lower() == "medium":
return level2
if level.lower() == "hard":
return level3
else:
print "Error"
index += 1
if index < 3:
return level_selection()
return
level1 = "You selected easy"
level2 = "You selected medium"
level3 = "You selected hard"
Another thing, if you really need global variables is to have a class member variable that holds your Index.
class VARS(object):
index = 0
VARS.index += 1
print(VARS.index)
>1
if you're newbie to python i highly recommend you to use python version 3.
python reads the codes line by line, that means that you can not call a variable before assign it.
the global variables are accessible inside the functions and classes, or by other meaning the variables are inherited inside functions and classes and no need to use global.
as a good practice:
so in your case the code is going to be:
index = 0 #global scope
def level_selection(dx):
my_local_index = dx #creating a new variale
level1 = "You selected easy" #local variables
level2 = "You selected medium" # not accessible outside of this scope
level3 = "You selected hard"
level = raw_input("Choose the desired level of difficulty: easy, medium or hard")
if level.lower() == "easy":
return level1
if level.lower() == "medium":
return level2
if level.lower() == "hard":
return level3
else:
print "Error"
my_local_index += 1
if my_local_index < 3:
return level_selection(my_local_index)
else:
exit()
# calling the function and passing a argument to it
level_selection(index)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With