我有一些代码要求用户猜测计算的答案,然后告诉他们他们是正确的或尝试找出他们出错的地方。我在其中使用了 while 循环,但有时它会卡住,有没有办法为所进行的猜测添加计数器,并在 5 次错误猜测后中断 while 循环?这是到目前为止我的代码的一部分:
\n#define correct answer for A\nAc=L*xm\n#ask user to work out A (monthly interest * capital)\nwhile True:\n A= raw_input("What do you think the monthly interest x the amount you are borrowing is? (please use 2 d.p.) \xc2\xa3")\n A=float(A)\n #tell user if they are correct or not\n if A==round(Ac,2):\n print("correct")\n break\n elif A==round(L*x,2):\n 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")\n continue\n elif A==round(L/(x*100),2):\n 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")\n continue\n else:\n print("Wrong, it seems you have made an error somewhere, you should have done the loan amount multiplied by the monthly rate")\n continue\nRun Code Online (Sandbox Code Playgroud)\n
标准库的itertools提供了一个向上计数的迭代器:
import itertools
for i in itertools.count():
print(i)
Run Code Online (Sandbox Code Playgroud)
您可以设置start和step:
# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) --> 2.5 3.0 3.5 ...
Run Code Online (Sandbox Code Playgroud)
Pythonic方式是
max_guesses = 5
solution = ... # Some solution
guessed = False
for wrong_guesses in range(1, max_guesses + 1):
guess = ... # Get Guess
if guess == round(solution, 2):
print("correct")
guessed = True
break
...
else:
print(f"You have exceeded the maximum of {max_guesses} guesses")
Run Code Online (Sandbox Code Playgroud)
这样循环就执行了大部分max_guesses时间。else仅当循环因break语句而未结束时(即没有正确猜测时)才会执行该块。
请注意,max_guesses + 1because是区间[low, high)(不包括上限)range上的迭代器。因此,要从 1 运行到 max_guesses,我们必须 +1。
一般来说,它应该看起来像这样:
i = 0
while i < max_guesses:
i+=1
# here is your code
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58706 次 |
| 最近记录: |