'Calling functions with variables multiple times

I'm making a program for a school project and I'm having an issue.

I have defined a function called DidThisWork like so:

def DidThisWork():
    global DidThisWork
    DidThisWork = input('\n\nDid this solution work? - ').lower()

Throughout my code, I want to call this function multiple times, however, I'm not able to. Is there a way, to call it multiple times, and like reset the DidThisWork variable inside the function after I used it in if statements?



Solution 1:[1]

You define a function def DidThisWork(): then within that very function you overwrite the newly created DidThisWork variable (which points to the function) to the result of your input(..) call.

So at the first call to DidThisWork(), the DidThisWork variable no longer points to the function, rather to the string returned by input(...).

If you rename either the function or the variable storing the string returned by input() it should work.

By the way, there are some naming conventions in Python you may want to look into https://www.python.org/dev/peps/pep-0008/#id30. Typically you'd use snake_case instead of camelCase and not only start a class with an upper case letter

worked = None

def did_this_work():
    global worked
    worked = input('\n\nDid this solution work? - ').lower()

print(worked)
did_this_work()
print(worked)
did_this_work()
print(worked)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ted