2017-02-04 100 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