修复Python Guessing Game不计算错误尝试的次数

时间:2019-05-26 17:17:29

标签: python

运行用于猜测游戏的Python代码-如果猜测数字超出范围-则不希望其计入尝试次数。代码可以工作,但是会把错误的数字计为尝试次数。

我的代码:

import random

print("The number is between 1 and 10")
print("You have 5 tries!")

theNumber = random.randrange(1,10)
maxTries = 5
tries = 1
guess = int(input("Take a guess: "))


while ((tries < maxTries) & (guess != theNumber)):  
    try:                    
        if guess > theNumber:
            print("Guess lower...")
        elif guess < theNumber:
            print("Guess higher...")        
        if guess > 10:
                raise ValueError

    except ValueError:
            print("Please enter a numeric value between 1 and 10.")
            #continue

    guess = int(input("Guess again: "))
    tries = tries + 1


    if(guess == theNumber):
        print("You guessed it! The number was", theNumber)
        print("And it only took you", tries, "tries!\n")
    else:
        print("You failed to guess", theNumber, "!")

只要猜测在1到10之间,它就可以连续猜测最多5次。如果超出此范围,则不会算作一次尝试,而是告诉用户“请输入1到10之间的数字”。 )。代码是做什么的-当我不希望它那样工作时,它只是计算尝试次数。

1 个答案:

答案 0 :(得分:0)

尝试这个:

url