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

时间:2019-02-17 21:25:12

标签: python

因此,我尝试获取我的Ask_Number与我的猜谜游戏配合。由于某些原因,游戏代码不会重新确认对Ask_Number的响应是整数。我也尝试定义响应,最终以不同的方式破坏了代码。我对这些东西发疯了。这是代码:

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

如果你们能帮助我阐明一些很棒的事情。

1 个答案:

答案 0 :(得分:1)

这令人困惑:

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
相关问题