【问题标题】:for statement implementation for try counting in python在python中尝试计数的语句实现
【发布时间】:2017-10-19 12:47:14
【问题描述】:

我希望使用数组计数和 for 语句在循环中检查输入值是否在 [0, 2] 范围内,当用户尝试输入错误值时打印“您超出了最大尝试次数” 3次以上,代码为:

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")

【问题讨论】:

  • 您在一些地方有拼写错误和缩进问题。在这实际的代码?
  • 你的内循环基本上违背了外循环的目的。为什么不使用一个 single 循环来记录尝试次数并检查有效输入。如果输入有效或已超过最大尝试次数,则退出循环。
  • @Carcigenicate 是的,我正在从头开始学习 python,所以我没有注意到一些拼写错误和缩进错误

标签: python arrays for-loop


【解决方案1】:

你把事情复杂化了。这个怎么样:

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")

【讨论】:

    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 2012-02-19
    • 2020-02-03
    • 1970-01-01
    • 2016-10-02
    • 2012-08-14
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多