用于在python中尝试计数的语句实现
问题描述:
我希望使用数组计数和for语句检查循环中输入值是否在[0,2]范围内打印“您超出了最大尝试次数”时用户试图输入一个错误的值的3倍以上,代码:用于在python中尝试计数的语句实现
a=int(raw_input("a "))
count=[1,2,3]
attemp=1
for i in count:
while (a<0 or a>2):
print ("WRONG")
a=int(raw_input("a"))
if (a>=0 and a<= 2):
i=4
else:
i+=1
attempt=i
if(attempt<=3):
print ("You needed %i" %attempt)
else:
print ("You exceeded the maximum amount of tries")
我遇到的逻辑问题,当我执行代码,我可以输入非有效值的无限量时的最大数量的尝试应该是3,所以它不会达到print ("You exceeded the maximum amount of tries")
答
你是过于复杂的事情。怎么样:
a = -1
attempt = 0
while not 0 <= a <= 2:
attempt += 1
if attempt == 3:
break
a = raw_input('a ')
if attempt < 3:
print ("You needed %s" % attempt)
else:
print ("You exceeded the maximum amount of tries")
你在几个地方有错别字和缩进问题。在这个实际的代码? – Carcigenicate
你的内部循环基本上破坏了外部循环的目的。为什么不有一个* single *循环既能保持尝试次数,又能检查有效输入。如果输入有效或超过最大尝试次数,则退出循环。 –
@Carcigenicate是的,我从头学习python,所以我没有注意到一些拼写错误和缩进错误 – Angelixus