How do you get a changing variable into a python function

Question:

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.

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)
Asked By: Bow the bro

||

Answers:

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"})
Answered By: Samwise

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)
Answered By: user19056900
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.