I have a question. What is wrong with this loop? I'm writing a number-guessing mini-game. The problem is that when the user enters the correct number on the second or third try, the loop still forces the user to 'try again' even though the correct number was entered but not the first time. The rule of the game is 4 chances to guess the other player's number
def do_action_to_guess(first_number: int, second_number: int):
counter = 0
while counter < 4:
if first_number != second_number:
counter = 1
second_number = int(input('Try again'))
elif first_number == second_number:
print('That is correct number')
break
else:
print('Out of chances')
return counter
CodePudding user response:
I don't run into the issue you're describing. One issue that does occur is that if you make the correct guess on the fourth guess, it claims you are incorrect and then runs out of chances. This is because on turn i you are actually checking the answer from turn i-1. Instead of using the second_number
argument, you should just ask for the second_number
at the beginning of the loop and then check the condition.
def do_action_to_guess(first_number: int):
counter = 0
while counter < 4:
second_number = int(input('Guess the number'))
if first_number != second_number:
counter = 1
print('Try again')
elif first_number == second_number:
print('That is correct number')
break
else:
print('Out of chances')
return counter
CodePudding user response:
Use a for loop to repeat it 4 times instead of counter. Never use counter
or guesses_left
variables. It causes confusion and makes it a lot harder
def do_action_to_guess(first_number: int, second_number: int):
for i in range(4):
#Your main code goes here
#for example
guess = input('Please select a number!\n')
if first_number != second_number:
second_number = int(input('Try again'))
elif first_number == second_number:
print('That is correct number')
else:
print('Out of chances')
I would need to see your other code in order to plug it in to the for loop