0

我正在制作一个简单的“猜一到十之间的数字”游戏。我已经使用了一些基本的错误处理并打印了随机模块生成的数字以用于测试目的。

但是我想知道是否有一种不那么冗长的方式来写这个。

这是代码:

import random

while True:

    """Variable declaration"""
    number_of_attempts = 1
    number = random.randrange (1,11)
    print (number)
    print("Time to play a guessing game! Muhahaha...")


    """Error handling and main game code/while loop"""

    while True:

        try:
            guess = int(input("Guess a number between one and ten."))

        except ValueError:
            print("Input a whole number between one and ten silly!")
            continue

        if guess >= 1 and guess <= 10:
            pass
        else:
            print("Input a number between one and ten silly!")
            continue   

        if guess == number:
            print("You were successful and it took you", number_of_attempts, "attempts!!!")
            break

        else:
            print("Try again!")   
            number_of_attempts = number_of_attempts +1

    """Game Exit/Restart"""

    play_again = input("Would you like to play again, y/n?")

    if "y" in play_again or "yes" in play_again:
        continue

    else:
        break         

谢谢,

4

2 回答 2

2
if guess >= 1 and guess <= 10:

可以写成:

if 1 <= guess <= 10:

此外,您的第一个条件可以简单地写为:

if not 1 <= guess <= 10:
    print("Input a number between one and ten silly!")
    continue

但这也可以放在try位中,避免你写continue两次:

try:
    guess = int(input("Guess a number between one and ten."))
    if not 1 <= guess <= 10:
        print("Input a number between one and ten silly!")
        continue
except ValueError:
    print("Input a whole number between one and ten silly!")
    continue

最后你的最后一个条件可以简单地是:

if play_again not in ('y', 'yes'):
    break

continue不需要。

您可能还希望将所有这些都包装到一个函数中,以摆脱那些无限的 while 循环并阻止您使用continue等等break

于 2013-10-08T11:12:30.830 回答
0

为什么不将实际条件放在 while 循环上,这样您就不必寻找中断来理解循环?它会让你的代码更清晰、更小。

 if guess == number:
        print("You were successful and it took you", number_of_attempts, "attempts!!!")
        break

例如,如果您将guess == number 作为while 循环条件,那么打印将是循环之后的第一件事。将guess 初始化为-1,所以它总是第一次工作。再次播放 if 语句也可以有条件地消失在循环中。

于 2013-10-08T11:24:16.893 回答