简体   繁体   English

当输入无效时,如何停止 for 循环迭代? (不允许使用 while 循环)- Python

[英]How can i stop a for-loop iterating when the input is not valid? (not allowed to use a while loop) - Python

for i in range (0, 3): 
    
    print() # When iterates creates a space from last section
    
    raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
    
    days_late = int(input("How many days late was that student (0 - 5)?: "))
    
    penalty = (days_late * 5)
    
    final_mark = (raw_mark - penalty)

    # Selection for validation 
    
    if 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark >= 40:
        
        print("Student ID:", str(student_id[i]))
        
        print() # Spacing for user readability
        
        print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
              str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
        
        print()
        
        print("This means that the result is now:", final_mark,"(this was not a capped mark)")

         
        
    elif 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark < 40: # Final mark was below 40 so mark must be capped
        
        print("Student ID:", str(student_id[i]))
        
        print()
        
        print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
              str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
        
        print()
        
        print("Therefore, as your final mark has dipped below 40, we have capped your grade at 40 marks.")

        
    else:
        print("Error, please try again with applicable values")

At the else i would like the loop to loop back through but not having iterated i to the next value, so that it can be infinite until all 3 valid inputs are entered... cannot use a while loop nor can i put the if - elif- else outside the loop.在 else 中,我希望循环返回但没有将 i 迭代到下一个值,这样它就可以是无限的,直到输入所有 3 个有效输入......不能使用 while 循环,也不能放置 if - elif- else 在循环之外。 Nor can i use a function :(我也不能使用函数:(

Try something like this.尝试这样的事情。 You can keep track of the number of valid inputs, and only stop your loop (the while ) once you hit your target number.您可以跟踪有效输入的数量,并且只有while达到目标数量后才停止循环( while )。

valid_inputs = 0

while valid_inputs <= 3:
   ...

   if ...:
      ...
   elif ...:
      ...
   else:
      # Immediately reset to the top of the while loop
      # Does not increment valid_inputs
      continue

   valid_inputs += 1

You can put the input statement inside while loop containing try block.您可以将输入语句放在包含 try 块的 while 循环中。

for j in range(3): # or any other range
    try:
        raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))

        days_late = int(input("How many days late was that student (0 - 5)?: "))
        break
    except:
        pass

If you really cannot use a while loop...如果你真的不能使用 while 循环......

def get_valid_input():
   user_input = input(...)
   valid = True
   if (...):  # Do your validation here
      valid = False

   if valid:
      return user_input
   else:
      return get_valid_input()

for i in range (0, 3): 
   input = get_valid_input()
   # Do what you need to do, basically your program from the question
   ...
   ...

There are some additional gotchas here, as in you need to worry about the possibility of hitting the maximum recursion limit if you keep getting bad input values, but get_valid_input should ideally only return when you are sure you have something that is valid.这里还有一些额外的问题,因为如果您不断获得错误的输入值,您需要担心达到最大递归限制的可能性,但理想情况下get_valid_input应该只在您确定您有一些有效的东西时返回。

You can have your for loop behave like a while loop and have it run forever and implement your i as a counter.你可以让你的 for 循环表现得像一个 while 循环并让它永远运行并将你的 i 实现为一个计数器。 Then the loop can be terminated only if it ever hits 3 (or 2 so that you indices dont change), while otherwise it is set back to 0:然后循环只有在它达到 3(或 2,以便您的索引不会改变)时才能终止,否则它会被设置回 0:

cnt_i = -1
for _ in iter(int, 1):
    cnt_i += 1
    if ...

    else:
        cnt_i = 0
    if cnt_i == 2:
        break

But seriously, whatever the reason for not using a while loop, you should use it anyhow..但说真的,无论什么原因不使用 while 循环,你都应该使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何并行化这个 Python for 循环? - How can I parallelize this Python for-loop? 如何使用 for 循环/范围来结束 Python 中的特定字符输入? - How to use a for-loop/range to end a specific character input in Python? javascript for 循环不在 python 循环内迭代 - javascript for-loop not iterating within python loop 当循环在Python中运行到最后时,如何创建一个for循环,其中变量的值等于范围的停止值? - How do I create a for-loop where the variable's value is equal to the stop value of range when the loop runs to the end in Python? 如何编写while循环以使其在2个变量获得某些值时停止? (Python) - How can I write while loop in order to make it stop when 2 variables got certain values? (Python) 如何在 for 循环中添加/使用异常处理? - How Can I Add/use exception handling in a for-loop? 如何停止 While 循环? - How can I stop a While loop? 刚开始学习 python; 当我使用列表推导时,为什么这个 for 循环的打印不同? 我如何使循环相同? - New to learning python; why is the print for this for-loop different when I use a list comprehension? how do i make the loop be the same? 如何修复 python 数组中 for 循环的值错误? - How can I fix value error on for-loop in python array? 如何在python中的for循环中创建对象? - How can I create objects in a for-loop in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM