【问题标题】:How do I make sure a 1-D array is valid using a while statement?如何使用 while 语句确保一维数组有效?
【发布时间】:2018-10-10 16:24:44
【问题描述】:

我正在尝试检查每个整数(数组)是否有效(0 到 30 之间)。当告诉用户分数无效的行运行但变量似乎不是 False 时出现问题,我不知道为什么,有人可以解决这个问题吗?

这里是有问题的代码:

while valid_score == True and program_running == True:
      for counter in range(0,6):
            print("How mant points did player", counter + 1 ,"earn?") 
            score_earned[counter] = int(input())

            if score_earned[counter] < 0 or score_earned[counter] > 30: 
                  print("That value was invalid as it was lower than 0 or `above 30!")`
                  valid_score = False

            else:
                  valid_score = True


            total_score = score_earned[counter] + total_score

      valid_score = False

【问题讨论】:

  • 有什么问题?什么是回溯?
  • 不相关,但range(0, 6) 的第一个参数是不必要的。
  • while 循环在发现无效分数时没有退出的原因是因为在 while 循环检查它是否有效之前,您的 for 循环仍然会从 0 到 6 运行到完成。当您发现无效分数时,您可能希望跳出 for 循环。我也看不到 while 循环的意义,因为您总是在最后将 valid_score 设置为 False,因此 while 循环只运行一次。
  • 至少从您所展示的内容来看,您并没有在迭代之前创建数组/列表。在 while 循环之前设置 score_earned = [0 for x in range(6)]。还有问题吗?编辑 - 正如其他人提到的那样, for range(0, 6) 几乎否定了 while 循环的有用性。在 while 循环之前开始计数,它将代替计数器变量。
  • 您的问题相当混乱。 “变量似乎不是 False” 这里的“变量”是指valid_score 吗?在 while 循环结束时将其设置为 false。那么你的意思是它不是False 在for循环之后吗?为什么你有一个while循环,条件是valid_scoreTrue,当你在循环结束时将它设置为False,保证它在第一次迭代后退出?

标签: python arrays loops while-loop


【解决方案1】:

在将这些值传递给字典之前,您可以阻止尝试输入任何不在您想要的范围内的 points。 您可以使用仅接受 points 范围的 while 循环来执行此操作

score_earned = {}  
players = 5

for i in range(1, players +1):
    points = -1
    while points < 0 or points > 30:
        try:
            points = int(input('Enter points for player {} between 0 and 30: '.format(i)))
        except ValueError:
            print('Please enter points between 0 and 30')
    score_earned[i] = points

total_score = sum(score_earned.values())
print('The total score is: {}'.format(total_score))

【讨论】:

  • @G_M Op 将int 投射到输入中,而没有考虑输入non-ints,所以我不想添加另一个他们不关心或不达标的元素速度与
  • 现在似乎所有其他答案也没有考虑到这种可能性,也许添加它可以使您的答案作为一种更好的方式脱颖而出?
  • @G_M ty 感谢您的意见
  • @G_M 哈哈,我肯定是新人,我刚开始第二个月的编码工作,我只是在玩时间复杂性,希望我做得很好啊哈哈顺便偷了你的学习材料 :)
【解决方案2】:

我猜你误解了循环的工作原理

while valid_score == True and program_running == True: # <-- This will not break while running inner loop
      for counter in range(0,6): # <-- this loops independently
            ....

我的建议是将您的代码调整为如下所示:

  for counter in range(0,6):
        print("How mant points did player", counter + 1 ,"earn?") 
        score_earned[counter] = int(input())

        if score_earned[counter] < 0 or score_earned[counter] > 30: 
              print("That value was invalid as it was lower than 0 or `above 30!")`
              valid_score = False
              break # <-- this ends the loop early

        else:
              valid_score = True

        total_score = score_earned[counter] + total_score
        if not program_running == True:
              break

【讨论】:

    【解决方案3】:

    我继续制作了您的代码的工作版本。你似乎犯了几个错误。这应该有助于消除您的误解。考虑添加一个 type() 检查以防有人决定输入一个字符串。

    score_earned = {} #python dictionary is an associative array
    counter = 1
    valid_score = True
    
    while valid_score == True: #and program_running == True: #program_running variable is never assigned
        print("How mant points did player", counter, "earn?") 
        score_earned[counter] = int(input())
    
        if score_earned[counter] < 0 or score_earned[counter] > 30: 
            print("That value was invalid as it was lower than 0 or above 30!")
            valid_score = False
    
        total_score = score_earned[counter] + total_score #currently doing nothing with total_score
        counter += 1
    

    【讨论】:

      【解决方案4】:

      for 循环的目的有点令人困惑,因为您在 0 和 6 之间反复循环,而您可能只想使用 while 循环并在计数器值小于 6 时增加计数器值。

      我写了这个例子,它将我能理解的从你的代码逻辑转换为只有一个 while 语句:

      counter = 0
      valid_score = True
      program_running = True
      
      while valid_score and counter < 6 and program_running:
          print("How mant points did player", counter + 1 ,"earn?") 
          score_earned[counter] = int(input())
      
          if score_earned[counter] < 0 or score_earned[counter] > 30: 
              print("That value was invalid as it was lower than 0 or `above 30!")`
              valid_score = False
      
          total_score += score_earned[counter]  # Not sure you want to add to the total score when invalid
                                                # Probably better to add to total score in else statement
          counter += 1  # Increment counter variable keeping track of number of iterations
      

      您可能可以对其进行一些修改以匹配您的预期结果,但这应该有助于您了解如何更好地使用 while 循环和计数器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-18
        • 2012-02-01
        • 2018-10-11
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多