简体   繁体   中英

My while loop won't stop after a condition

I made a dice game and you have 3 goes and, if you don't guess it with the 3 goes, it will show you the number and say you lost but for me it only shows it if you don't guess it in 4 goes.

import random
import time

guess=3

print ("Welcome to the dice game :) ")
print ("You have 3 guess's all together!")
time.sleep(1)

dice=random.randint(1, 6)

option=int(input("Enter a number between 1 and 6: "))

while option != dice and guess > 0:
    option=int(input("Wrong try again you still have " + str(guess) + " chances remaining: "))
    guess=guess-1

    if guess == 0:
        print ("You lost")
        print ("The number was " + str(dice))

if option == dice:
    print ("You win and got it with " + str(guess) + " guess remaining")


and the result is:

Welcome to the dice game :) 
You have 3 guess's all together!
Enter a number between 1 and 6: 4
Wrong try again you still have 3 chances remaining: 4
Wrong try again you still have 2 chances remaining: 4
Wrong try again you still have 1 chances remaining: 4
You lost
The number was 2

A cleaner way to write this would be

import random
import time

guesses = 3

print("Welcome to the dice game :) ")
print("You have 3 guesses all together!")
time.sleep(1)

dice = random.randint(1, 6)

while guesses > 0:
    option = int(input("Enter a number between 1 and 6: "))
    guesses -= 1

    if option == dice:
        print(f"You win and got it with {guesses} guess(es) remaining")
        break

    if guesses > 0:
        print("Wrong try again you still have {guesses} guess(es) remaining")
else:
    print("You lost")
    print(f"The number was {dice}")

The loop condition only tracks the number of guesses remaining. If you guess correctly, use an explicit break to exit the loop. The else clause on the loop, then, is only executed if you don't use an explicit break .

You're giving the user an extra chance with this line: option=int(input("Enter a number between 1 and 6: ")) . Try declaring guess=2 instead.

Your code clearly grants the initial guess (before the loop), and then three more (within the loop). If you want it to be 3 guesses, then simply reduce your guess counter by 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM