I am wondering how I would go about getting different variable names into a function if that makes sense. I am trying to create a "portable" loop to make things easier and more structured in a text based adventure I am creating. Any help is appreciated. Code I have tried is shown below for an idea of what im trying to achieve.
edit: Apologies for stack making some of my code look like a header and a bottom text I am not sure how to fix it.
def incorrectAnswerLoop(answers, variable_name):
while True:
user_input=input()
if answers in user_input:
variable_name = user_input
break
else:
print("incorrect input")
continue
incorrectAnswerLoop({"katana", "claymore", "dagger"}, sword.type)
CodePudding user response:
Use return
instead of trying to modify one of the arguments. (You can use mutable args, or even mutate mutable objects in the outer scope, but don't -- just return the value you want to return.)
If your function returns the value, then the caller can simply assign the returned value to whatever variable it wants.
def incorrectAnswerLoop(answers):
while True:
user_input = input()
if user_input in answers:
return user_input
else:
print("incorrect input")
sword.type = incorrectAnswerLoop({"katana", "claymore", "dagger"})
CodePudding user response:
You can try using recursion instead of while loop and pass the input as parameters:
def incorrectAnswerLoop(answers, variable_name):
if not variable_name in answers:
print("incorrect input")
return incorrectAnswerLoop(answers, input())
return variable_name
sword_type = incorrectAnswerLoop({"katana", "claymore", "dagger"}, input())
print(sword_type)
or handling input within the function like this:
def incorrectAnswerLoop(answers):
if not (variable_name := input()) in answers:
print("incorrect input")
return incorrectAnswerLoop(answers)
return variable_name
sword_type = incorrectAnswerLoop({"katana", "claymore", "dagger"})
print(sword_type)