这个Python程序可以简化还是更好的编写?

时间:2012-05-08 01:30:39

标签: python syntax python-3.x

好的,所以我在过去的几天里学习了相当多的Python,两三个,我决定学习一些简单的东西,但有点娱乐,所以我创造了一个猜测游戏。

创建这个程序大约30分钟并让它100%工作后,我想知道是否有什么我可以做得更好等等。我想确保我从任何错误中吸取教训,所以我很感激!

所以这是代码:

import random

def guessingGame():

    randomNumber = random.randrange(1, 10)
    yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))

    while yourGuess != randomNumber:
        print("DOH! You Did Not Guess Right, TRY AGAIN")
        yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))
    else:
        if yourGuess == randomNumber:
            print("Congrats You Beat The Guess Game!")

playGame = input("Would You Like To Play The Guessing Game (Y/N): ")

if playGame == "Y" or playGame == "y":
    print("Okay Lets Play!")
    guessingGame()

elif playGame == "N" or playGame == "n":
    print("Okay Thanks Anyways!")
    break

再次感谢!

5 个答案:

答案 0 :(得分:4)

而不是

if playGame == "Y" or playGame == "y":
    print("Okay Lets Play!")
    guessingGame()

我有点喜欢

if playGame.lower() == "y":
    # ...

我更喜欢:

def quit():
    print("Okay Thanks Anyways!")


actions = {"y": guessingGame}
actions.get(playGame.lower(), quit)()

答案 1 :(得分:2)

我注意到的一些事情:

  • 您应该处理用户试图猜测看起来不像数字的情况,例如字母'a'。
  • Python样式指南说喜欢使用lower_with_underscores而不是CamelCase来获取变量名称。
  • yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))不必要地重复,请参阅下文,了解重构该部分的一种可能方法。

一般清理:

import random

def guessing_game():
  random_number = random.randint(1, 10)
  assert random_number in range(1, 11)
  your_guess = None
  while your_guess != random_number:
    try:
      your_guess = int(input("Take A Guess, Numbers 1 Through 10: "))
    except ValueError:
      print("That wasn't a number")
      continue

    if your_guess != random_number:
      print("DOH! You Did Not Guess Right, TRY AGAIN")
    else:
      print("Congrats You Beat The Guess Game!")
      break

play_game = None
while play_game not in ['y', 'n']:
  play_game = input("Would You Like To Play The Guessing Game (Y/N): ").lower()

if play_game == "y":
  print("Okay Lets Play!")
  guessing_game()
else:
  assert play_game == "n":
  print("Okay Thanks Anyways!")

答案 2 :(得分:2)

from random import randint

def getInt(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("That's no integer!")

def play():
    secret = randint(1,10)
    while True:
        guess = getInt("Take a guess (1-10):")
        if guess==secret:
            print("Congrats, you beat The Guess Game!")
            break
        else:
            print("D'oh! You guessed wrong. Try again!")

def main():
    while True:
        inp = input("Would you like to play The Guessing Game? (Y/N)").lower()
        if inp=="y":
            print("Okay, let's play!")
            play()
        elif inp=="n":
            print("Alright. Thanks anyways!")
            break
        else:
            print("You don't follow directions too good, eh?")

if __name__=="__main__":
    main()

答案 3 :(得分:1)

我想你可以在while循环中使用“break”语句,如

import random

def guessingGame():    
    randomNumber = random.randrange(1, 10)

    while True:

        yourGuess = input("Take A Guess, Numbers 1 Through 10: ")

        if !yourGuess.isdigit():
            print ("That's not a number!")
        elif int(yourGuess) not in range(1,10):
            print("I said between 1 and 10!")
        elif int(yourGuess) != randomNumber:
            print("DOH! You Did Not Guess Right, TRY AGAIN")
        else:
            break

    print("Congrats You Beat The Guess Game!")

playGame = input("Would You Like To Play The Guessing Game (Y/N): ")

if playGame.lower() == "y":
    print("Okay Lets Play!")
    guessingGame()

elif playGame.lower() == "n":
    print("Okay Thanks Anyways!")
    break

答案 4 :(得分:1)

阅读有关命名约定和Python编码风格的Pep 8文档。

import random

def guessing_game(x=1, y=10):
    """
    A simple number guessing game.
    """
    while int(input("Take A Guess, Numbers 1 Through 10: ")) \
                                          != random.randrange(x, y):
        print("DOH! You Did Not Guess Right, TRY AGAIN")

    print("Congrats You Beat The Guess Game!")

    if input("Would You Like To Play The Guessing Game (Y/N): ") == 'Y':
        print("Okay Lets Play!")
        guessing_game()
    else:
        print("Okay Thanks Anyways!")

if __name__ == '__main__':
    guessing_game(1, 10)