2015-11-13 131 views
-4
__author__ = 'Toby' 
error = 0 ## Sets a variable that allows a while loop to be used 
while error == 0: ## While loop so that the program will keep asking until a valid entry is inputted 
    try: 
     number1 = float(input("please enter 1st number")) ## The first number is inputted and stored as a variable 
    except ValueError: ## Error Capture so the user can try again if invalid entry is enterd 
     print("Please enter a number, it can be a decimal or an integer") 
     print("try again") 
    else: 
     break 
error2 = 0 
while True: ## While loop so that the program will keep asking until a valid entry is inpuuted 
    try: 
     number2 = float(input("please enter 2nd number")) ## Takes second number and inouts into a different vairable 
    except ValueError: 
     print("Please enter a number, it can be a decimal or an integer") 
     print("try again") 
    else: 
     break 
error3 = 0 
while True: ## While true means,run the loop below so that the user can input a 3rd number,and the prgram will keep asking until it is a valid entry 
    try: 
     number3 = float(input("please enter 3rd number")) 
    except ValueError: 
     print("Please enter a number, it can be a decimal or an integer") 
     print("try again") 
    else: 
     break 

if number1 == number2 and number2 == number3: ## if statement to check that if all numbers are equal then an appropiate action can be carried out 
    print("SNAP!") 
else: 
    print("Sorry your numbers dotn match. do you want to play again?") 

我的任务是做一个蟒蛇游戏,然后有什么更好的办法,我可以做到这一点,以获得更多的分数?我在做GCSE计算机科学。谢谢Python捕捉游戏

+6

我投票结束这个问题作为题外话,因为我们不知道如何才能“获得更多的分数”。 – That1Guy

+3

请尝试询问[代码评论](http://codereview.stackexchange.com/)。如果您的代码是功能性的,他们应该乐于提供样式/优化提示。 – Kevin

+0

您可以从改善拼写开始。 ''对不起,你的号码不匹配,你想再玩一次吗?“有两个字符倒过来,缺少一个首都。 – Mast

回答

0

删除error,error2error3,因为它们不使用。

摆脱重复。创建一个提示'1st''2nd''3rd'的功能。将返回值分配给number1number2number3

比较浮动并不总是相等。创建一个close函数来检查它们是否足够接近。

创建一个单独的函数来评估snap条件。给它可以运行的doctests来验证行为。

摆脱评论。他们可以是有用的,但往往是杂乱的代码除臭剂。如果您使用良好的函数,变量和参数名称进行说明,则注释会变得多余。

__author__ = 'Pete' 

def main(): 
    number1 = prompt(nth='1st') 
    number2 = prompt(nth='2nd') 
    number3 = prompt(nth='3rd') 

    if snap(number1, number2, number3): 
     print("SNAP!") 
    else: 
     print("Sorry your numbers don't match. Do you want to play again?") 

def prompt(nth): 
    while True: 
     try: 
      return float(input("please enter the {nth} number".format(nth=nth))   
     except ValueError: 
      print("Please enter a number, it can be a decimal or an integer") 
      print("try again") 

def snap(a, b, c): 
    """ 
    >>> snap(1, 1, 1) 
    True 

    >>> snap(1.0, 1, 5/5.0) 
    True 

    >>> snap(1, 2, 10) 
    False 
    """ 
    return close(a, b) and close(b, c) 

def close(a, b): 
    return abs(a - b) < 1e-6 

if __name__ == '__main__': 
    main()