无法让我的猜谜游戏将Ask_数字识别为整数

2024-05-18 06:12:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着让我的Ask_号码配合我的猜谜游戏。由于某些原因,游戏代码无法确认对Ask_编号的响应是整数。我也尝试过定义响应,结果以不同的方式破坏了代码。我被这些东西弄疯了。代码如下:

import sys

def ask_number(question, low, high):
    """Ask for a number from 1 to 100."""

    response = int(input(question))

    while response not in range(low, high):
        ask_number("Try again. ", 1, 100)
        break
    else:
        print(response)
        return response


ask_number("Give me a number from 1-100: ", 1, 100)

print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible. OR ELSE!!!\n")
le_number = ask_number
guess = int(input("Take a Friggin Guess: "))
tries = 1
# guessing loop
while guess != le_number:
    if guess > le_number:
        print("Lower Idgit....")
    else:
        print("Higher Idgit...")

    if tries > 5:
        print("Too bad Idgit. You tried to many times and failed... What a shocker.")
print("The number was", le_number)
input("\n\nPress the enter key to exit Idgit")
sys.exit()

guess = int(input("Take a guess:"))
tries += 1


print("You guessed it! The number was", le_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit Idgit")

如果你们能帮我解释一下,那就太好了


Tags: to代码lenumberinputresponseexitit
1条回答
网友
1楼 · 发布于 2024-05-18 06:12:01

这令人困惑:

response = int(input(question))

while response not in range(low, high):
    ask_number("Try again. ", 1, 100)
    break                              # will leave the loop after 1 retry
else:                                  # so the while is superflous 
    print(response)                    # and the else part is never executed if you break
    return response                    # from a while, only if it evaluates to false

这是:

le_number = ask_number

不执行函数-您需要调用它:

le_number = ask_number("some question", 5,200) # with correct params

# or
while guess != ask_number("some question", 5,200):    # with correct params

最好在函数内部执行“更多”。这个function的功能是为您提供一个数字-所有需要做的事情都在它里面-您可以轻松地测试/使用它,并确保从中获得一个数字(除非用户杀死您的程序、死亡或计算机崩溃):

def ask_number(question, low, high):
    """Ask for a number from low to high (inclusive)."""
    msg = f"Value must be in range [{low}-{high}]"
    while True:
        try:
            num = int(input(question))
            if low <= num <= high:
                return num
            print(msg)
        except ValueError:
            print(msg)


ask_number("Give me a number: ",20,100)

输出:

Give me a number: 1
Value must be in range [20-100]
Give me a number: 5
Value must be in range [20-100]
Give me a number: tata
Value must be in range [20-100]
Give me a number: 120
Value must be in range [20-100]
Give me a number: 50

这样,只有有效值才能转义函数

有关更多信息,请阅读Asking the user for input until they give a valid response上的答案


the_given_number = ask_number("Give me a number: ",20,100)

# do something with it 
print(200*the_given_number)  # prints 10000 for input of 50

相关问题 更多 >