[ Python: loop error in Python Programming for Absolute Beginner "games" module ]
I'm learning Python and have hit a snag in this code. I have even pulled down the author's code and it has the same problem. :(
After importing the "random" module and the "games" module, which includes the "ask_number()" function and the class definition for a "Player," we have:
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2-5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
The "ask_number()" function looks like this:
def ask_number(question, low, high):
"""Ask for a number within a range."""
response = None
while response not in range(low, high):
response = int(input(question))
return response
When the program is run, however, the question "How many players? (2-5):" appears ad infinitum, regardless of what number is input as a response. Clearly it seems some kind of erroneous loop has been set up, but I can't figure out what it is for the life of me (that's why I'm an "absolute beginner," haha!).
Thanks in advance for returning my sanity to me! :)
EDITED: Since I thought the problem was merely with the syntax of the ask_number() function, I didn't want to append a lot of extraneous code. Learned that lesson! :) This is the full loop, so it does seem that again has a changeable value. (Note that the "ask_yes_no()" function is also in the "games" module.)
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2-5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
Answer 1
you are saying
while again != "n":
but you never set again! Because again never equals 'n' it never exits the loop
Answer 2
You are never changing the value of again
. In order to fix this you could add this
again = raw_input("Play again?: ")
at the end of the while
loop.