我如何改进这段代码或使其更有效率?
import random
menu_check = True
# 'checker', compares userNums and winningNums to see if they have won or lost
def checker(userNums, winningNums):
if userNums == winningNums:
print ("\nCongratulations! You Win $100!\n")
print ("Your numbers: ", userNums)
print ("The winning lottery numbers are: ", winningNums, "\n")
else:
print ("\nSorry, you lose...\n")
print ("Your numbers: ", userNums)
print ("The winning lottery numbers are: ", winningNums, "\n")
# 'getUserNums', gets user numbers and puts into a sorted list
def getUserNums():
userNums = []
for x in range(3):
nums = int(input("Pick a number 0 through 9: "))
if 0 <= nums <= 9:
userNums.append(nums)
else:
input("Error! Invalid input. Press any key to continue...")
nums = int(input("Pick a number 0 through 9: "))
userNums.append(nums)
return sorted(userNums)
# 'getWinningNums', creates a sorted list with random nums ranging from 0-9 with a range of 3 values
def getWinningNums():
return sorted(random.sample(range(0,10), 3))
# 'menu', creates the main menu to choose game or exit program
def menu():
print (30 * "-", "LOTTERY MENU", 30 * "-")
print ("1. [Play Pick-3]")
print ("2. Exit")
print (75 * "-")
# 'main', calls the other functions
def main():
userNums = getUserNums()
winningNums = getWinningNums()
checker(userNums, winningNums)
#
while menu_check:
menu()
choice = input("\nEnter your choice[1-2]: ")
if choice == '1':
print (23 * "-")
print ("[Play Pick-3] selected!")
print (23 * "-")
menu_check = False
main()
elif choice == '2':
print ("\nThanks for playing!\n")
menu_check = False
else:
input("Error! Invalid input. Press any key to continue...\n")发布于 2016-06-23 06:59:18
在大多数情况下,这是非常好的代码imho。你有一个清晰和一贯的风格。我真的很喜欢你把你的函数分解成逻辑函数。然而,您缺少了编写一个更节奏式的函数,而且代码的一部分是非常硬编码的。
你有一个非常一致的编码风格,这是很好的。然而,您似乎使用#C命名约定和形成而不是pythonic。变量名使用camelCase,但是在Python中类名推荐UpperCamelCase,常量使用CAPITALIZED_WITH_UNDERSCORES,其他名称使用lowercase_separated_by_underscores。
python风格的黄金标准是PEP 8。它详细地解释了如何构造代码。我由衷地建议浏览一下,然后按照它来做。
您应该使用if __name__ == "__main__":模块在您的回答中。这允许您为以后重用这些函数,并且总是使用它是一件很棒的事情。
getUserNums()有点奇怪。如果我的输入不正确,则引发错误。然而,第二次我的输入是不正确的,它通过的很好。您可以使用while循环来解决这个问题。
def getUserNums():
userNums = []
while len(userNums) < 3:
nums = int(input("Pick a number 0 through 9: "))
if 0 <= nums <= 9:
userNums.append(nums)
else:
input("Error! Invalid input. Press any key to continue...")上面这个片段的第二个问题是,您可以不止一次地猜测相同的数字!解决这个问题的一个快速方法是将if 0 <= nums <= 9替换为
if 0 <= nums <= 9 and nums not in UserNums第三个也是最后一个问题是,如果输入不是整数,程序就会崩溃。对此有许多解决方案,下面给出了一个快速而肮脏的解决方案
nums = input("Pick a number 0 through 9: ")
try:
nums = int(nums)
except:
print("Sorry your input must be an integer!")
continuecontinue关键字很重要,因为它跳过了循环的其余部分。如果你移除它会发生什么?
您已经在menu()函数中重复使用了print (更好的名称可能是print_menu())。这个问题可以按以下方式解决
def menu():
print (30 * "-", "LOTTERY MENU", 30 * "-",
'1. [Play Pick-3]",
'2. Exit',
75 * "-")在您的代码中,我们找到了所谓的幻数。它们是具有无法解释的含义或多次出现的唯一值,可以(最好)替换为命名常量。例如,数字的范围或30*'-'。它们应该最优地替换为指定的常量。
在下面的代码中,我更改了您的变量名,替换了所有神奇的数字。我也对你的主要功能做了一些小小的改动。
拉斯利,我让你的Error消息更具描述性:input("Error! Invalid input. Press any key to continue..."),首先,错误是什么?我的输入有什么问题?第二,让用户按任意键继续是很奇怪的。
import random
NUMBER_OF_PICKS = 3
MIN_PICK = 1
MAX_PICK = 11
WINNINGS = 100
OFFSETT = 4
# 'checker', compares userNums and winningNums to see if they have won or lost
def checker(userNums, winningNums):
if userNums == winningNums:
print ("\nCongratulations! You Win ${}!".format(WINNINGS),
"\nYour numbers: ", userNums,
"\nThe winning lottery numbers were: ", winningNums, "\n")
else:
print ("\nSorry, you lose...",
"\nYour numbers: ", userNums,
"\nThe winning lottery numbers were: ", winningNums, "\n")
# 'get_user_nums', gets user numbers and puts into a sorted list
def get_user_nums():
userNums = []
while len(userNums) < NUMBER_OF_PICKS:
nums = input("Pick a number {} through {}: ".format(MIN_PICK, MAX_PICK))
try:
nums = int(nums)
except:
print("Sorry your input must be an integer!")
continue
if MIN_PICK <= nums <= MAX_PICK:
if nums not in userNums:
userNums.append(nums)
else:
print("Error! You have already picked this number")
else:
print("Error! Your number was not in range")
return sorted(userNums)
# 'get_winning_nums', creates a sorted list with random nums ranging from 0-9 with a range of 3 values
def get_winning_nums():
return sorted(random.sample(range(MIN_PICK, MAX_PICK), NUMBER_OF_PICKS))
# 'menu', creates the main menu to choose game or exit program
def lottery_menu():
name = ' '*int(OFFSETT/2) + "LOTTERY MENU"
dotted = (OFFSETT+len(name))*'-'
options = ["[Play Pick {}]".format(NUMBER_OF_PICKS),
"[Exit]"]
print('{} \n{} \n{}'.format(dotted, name, dotted))
for i, opt in enumerate(options):
print(i+1, opt)
print(dotted)
def play_pick_n():
userNums = get_user_nums()
winningNums = get_winning_nums()
checker(userNums, winningNums)
# 'main', calls the other functions
def main():
lottery_menu()
while True:
choice = input("\nEnter your choice[1-2]: ")
if choice == '1':
string = "\n[Play Pick {}]".format(NUMBER_OF_PICKS) + "selected!"
dotted = '\n'+ len(string) * "-"
print(dotted,
string,
dotted)
play_pick_n()
break
elif choice == '2':
print ("Thanks for playing!\n")
break
print("Error! Invalid input. Press any key to continue...\n")
if __name__ == '__main__':
main()https://codereview.stackexchange.com/questions/132810
复制相似问题