2017-02-04 101 views
0

我有一些代码要求用户猜测计算的答案,然后要么告诉他们他们是正确的,要么试图找出他们出错的地方。我在此使用了一个while循环,但有时它会卡住,是否有一种方法可以对所采用的猜测添加计数器,并在5次错误的猜测后打破while循环?添加计数器while循环python

回答

1

一般来说,应该是这样的:

i = 0 
while i < max_guesses: 
    i+=1 
    # here is your code 
0

你只需要创建一个wrong_guess计数器,并停止while循环,如果wrong_guess> = 5:

wrong_guess = 0 
Ac=L*xm 
#ask user to work out A (monthly interest * capital) 
while wrong_guess < 5: 
    A= raw_input("What do you think the monthly interest x the amount you are borrowing is? (please use 2 d.p.) £") 
    A=float(A) 
    #tell user if they are correct or not 
    if A==round(Ac,2): 
     print("correct") 
     break 
    elif A==round(L*x,2): 
     print("incorrect. You have used the APR rate, whic is an annual rate, you should have used this rate divided by 12 to make it monthly") 
    elif A==round(L/(x*100),2): 
     print("incorrect. You have used the interest rate as a whole number when you should have used it as a decimal, and divided it by 12 for the monthly rate") 
    else: 
     print("Wrong, it seems you have made an error somewhere, you should have done the loan amount multiplied by the monthly rate") 
    wrong_guess += 1 
+2

有没有必要写'wrong_guess + = 1'这是因为当答案是正确的时OP被打破。 – MaLiN2223

1

Pythonic方式是

max_guesses = 5 
guessed = False 
for wrong_guesses in range(max_guesses): 
    if A==round(Ac,2): 
     print("correct") 
     guessed = True 
     break 
    ... 
else: 
    print("You have exceeded the maximum of {} guesses".format(max_guesses)) 
if not guessed: 
    wrong_guesses += 1 

这样循环最多执行max_guesses次。 else块仅在循环未因语句break而结束时执行,即当没有正确的猜测时。

注意if not guessed最后是为了迎合上次错误的猜测,因为循环以wrong_guesses ==(max_guesses - 1)结束。这是因为range是区间[0,max_guesses)(不包括上限)的迭代器。

1

只需创建一个变量来存储不正确的猜测和使用如果在5个incorrects发生,以决定条件,停止如下所示的loop.As:

Ac=L*xm 
count = 0 #variable to store incorrect guesses 
#ask user to work out A (monthly interest * capital) 
while True: 
    if count == 5: #IF COUNT(incorrect) is 5 times 
     break #stop loop 
    else: # if not continue normally 
     A = raw_input("What do you think the monthly interest x the amount you are borrowing is? (please use 2 d.p.) £") 
     A = float(A) 
     # tell user if they are correct or not 
     if A == round(Ac, 2): 
      print("correct") 
      break 
     elif A == round(L * x, 2): 
      print(
       "incorrect. You have used the APR rate, whic is an annual rate, you should have used this rate divided by 12 to make it monthly") 
      count += 1 
     elif A == round(L/(x * 100), 2): 
      print(
       "incorrect. You have used the interest rate as a whole number when you should have used it as a decimal, and divided it by 12 for the monthly rate") 
      count += 1 
     else: 
      print(
       "Wrong, it seems you have made an error somewhere, you should have done the loan amount multiplied by the monthly rate") 
      count += 1