user7298470
user7298470

Reputation:

Logical error causing infinite while loop

When the user enters the number 0 and the program does task0 the while loop does not end as I intended it to. Why is this and how do I fix it?

def task0():
    print("Goodbye")
    end = "true"
end = "false"
while end != "true":
    print()
    tasknum = input("Which task would you like to see? ")
    print()
    task = "task" + tasknum
    methodToCall = globals()[task]
    result = methodToCall()

Upvotes: 1

Views: 140

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160417

It is best to communicate with your function by using return values, not altering global names.

Also, use True and False, there's no need to use string comparison.

In short, return True from your function and assign it to end:

def task0():
    print("Goodbye")
    return True

end = False
while not end:
    print()
    tasknum = input("Which task would you like to see? ")
    print()
    task = "task" + tasknum
    methodToCall = globals()[task]
    end = methodToCall()

you then check on that and end appropriately.

Upvotes: 4

Related Questions