Reputation: 201
I'm a noob trying to learn Python. I made a function to allow a user to remove items from a list, by selecting them 1 at a time, then removing same from the list (basically, to choose dice to reroll in my Yahtzee game). So, I want a user to be able to remove 1 item or more from a list, and for the while loop to exit when the user decides on line 22 that they do not want to reroll any more dice. The function seems to works fine, unless the user selects 1 dice to reroll (say 6), then selects 'y' to reroll another, then selects another dice, and then select's n, which causes the while loop to incorrectly loop between lines 21 and 25 and back to 21 (requiring the user to enter n twice, rather than once to exit the loop. My code on Repl.it is here
Again, the problem only seems to occur if you choose at least 2 dice to remove.
dice1 = [1,2,3,4,5,6]
def sub_dice():
while True:
try:
print 'line 6'
subtract1 = int(raw_input('What dice do you want to reroll?'))
except ValueError:
print('Enter a number corresponding to the dice you want to reroll')
continue
if subtract1 not in dice1:
print('You must select 1 of the dice from the table to remove')
else:
break
if subtract1 in dice1:
dice1.remove(subtract1)
print "The remaining dice are " + str(dice1)
while True:
print 'line 21'
more = raw_input("Do you want to reroll another dice, 'Y' or 'N?'")
if more.lower() == 'n':
print 'line 25'
print "On that turn, you kept " + str(dice1)
return len(dice1)
break
elif (more.lower() != 'y') and (more.lower() != 'n'):
print('You must select Y or N')
print 'line 32'
elif more.lower() == 'y':
print 'line 35'
sub_dice()
sub_dice()
*You can see the problem by entering 6 for example, then y, then 5, and then 'n', at which point you will see it loops back to line 21 and again asks if you want to reroll another dice, even though you have indicated no.
Upvotes: 0
Views: 129
Reputation: 802
The reason for the behavior is that you are calling sub_dice() from within itself. Read about recursive functions, because I'm not sure you intended to do this.
When you type 'n' you are exiting from the nested sub_dice() call, so it just returns to the original call instead of exiting the program like you expect.
Upvotes: 1