gpt4 book ai didi

python - 可以简化或更好地编写此 Python 程序吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:31 24 4
gpt4 key购买 nike

好吧,在过去的两三天里,我学习了相当多的 Python,我决定利用我的知识创造一些简单但有趣的东西,所以我创造了一个猜谜游戏。

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

代码如下:

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

再次感谢!

最佳答案

代替

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

关于python - 可以简化或更好地编写此 Python 程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10491361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com