2016-07-15 566 views
0

我正在学习python,其中一个练习是制作一个简单的乘法游戏,每当你正确回答时进行。虽然我已经完成了游戏,但我希望能够计数尝试的次数,以便在我几次正确回答循环/函数时结束。我的问题是,在代码结束时,函数被再次调用,显然,尝试的次数可以追溯到我最初设置的次数。我怎么能去一点,这样我可以指望每个循环,并在指定的尝试次数?:计算循环的次数python

def multiplication_game(): 
    num1 = random.randrange(1,12) 
    num2 = random.randrange(1,12) 

    answer = num1 * num2 

    print('how much is %d times %d?' %(num1,num2)) 

    attempt = int(input(": ")) 

    while attempt != answer: 
     print("not correct") 

     attempt = int(input("try again: ")) 
    if attempt == answer: 
     print("Correct!") 

multiplication_game() 
+0

你能格式化你的代码吗?缩进不正确 –

+1

从代码中不清楚您是否递归调用它 - 您能格式化代码吗? – nagyben

+0

三种可能性:添加全局计数器变量;将当前的转数作为参数传递给函数,或(首选)将递归更改为另一个循环。 –

回答

1

end你可以在一个循环的结束环绕你的multiplication_game()电话。例如:

for i in range(5): 
    multiplication_game() 

将允许您在节目结束前玩5次游戏。如果你想真正地计算你正在使用哪一轮,你可以创建一个变量来跟踪,并在游戏结束时增加该变量(你可以把它放在函数定义中)。

1

我会用一个for环和break出来的:

attempt = int(input(": ")) 

for count in range(3): 
    if attempt == answer: 
     print("correct") 
     break 

    print("not correct") 
    attempt = int(input("try again: ")) 
else: 
    print("you did not guess the number") 

这里有else clauses for for loops一些文件,如果你想它是如何工作的更多信息。

0
NB_MAX = 10 #Your max try 
def multiplication_game(): 
    num1 = random.randrange(1,12) 
    num2 = random.randrange(1,12) 

    answer = num1 * num2 
    i = 0 
    while i < NB_MAX: 
      print('how much is %d times %d?' %(num1,num2)) 

      attempt = int(input(": ")) 

      while attempt != answer: 
       print("not correct") 

      attempt = int(input("try again: ")) 
      if attempt == answer: 
       print("Correct!") 
      i += 1 

multiplication_game()