简体   繁体   English

修复Python猜测游戏不计算错误的尝试

[英]Fix Python Guessing Game to not count erroneous tries

Running Python code for guessing game - if guess number outside of range - do not want it to count against tries. 运行用于猜测游戏的Python代码 - 如果猜测数字超出范围 - 不希望它计入尝试。 Code works but counts erroneous numbers as tries. 代码有效,但将错误的数字计为尝试。

My code: 我的代码:

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, "!")

It allows continued guessing up to 5 tries as long as guess is between 1 and 10. If outside of this range - it will not count as a try but tells the user to "Please enter a numeric value between 1 and 10"). 只要猜测在1到10之间,它就允许继续猜测最多5次尝试。如果超出此范围 - 它将不算作尝试但是告诉用户“请输入1到10之间的数值”)。 Which the code does - it just counts those tries when I do not want it to work that way. 代码的作用 - 当我不希望它以这种方式工作时,它只计算那些尝试。

Try this one: 试试这个:

import random

min_number = 1
max_number = 10
number = random.randrange(min_number, max_number + 1)
print(number) # To know the number you are guessing
maximum_tries = 5

print(f"The number is between {min_number} and {max_number}")
print(f"You have {maximum_tries} tries!")

guess = int(input("Take a guess: "))

j = 1

while True:

    if guess > max_number or guess < min_number:
        print("Please enter a numeric value between 1 and 10.")
        j = j - 1
    elif guess > number:
        print("Guess lower...")
        print("You failed to guess", j, "!")
    elif guess < number:
        print("Guess higher...")
        print("You failed to guess", j, "!")

    if guess == number:
        print("You guessed it! The number was", number)
        print("And it only took you", j, "tries!\n")
        break

    if j == maximum_tries:
        break

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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