如何使这段代码更简洁?

时间:2013-10-08 11:06:29

标签: python

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

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

这是代码:

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         

谢谢,

2 个答案:

答案 0 :(得分: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循环,并阻止您使用continuebreak这么多。

答案 1 :(得分:0)

为什么不把实际条件放在while循环上,这样你就不用去寻找中断了解循环?它会使你的代码更清晰,更小。

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

例如,如果你把guess == number作为while循环条件,那么print将是循环之后的第一件事。将guess初始化为-1,因此它始终在第一次运行。再次播放if语句也可以在条件循环中消失。