简体   繁体   English

即使条件为假,“While”循环仍在无限运行

[英]'While' loop is running infinitely even though the condition is false

There is a while loop in line 14. Even if I enter M or F, it still gives the input.第14行有一个while循环,即使我输入M或F,它仍然给出输入。 It doesn't continue.它不会继续。

import array

# Declaration of variables
Constnostudents = int(3)
StudentName = []
StudentGender = []

# Declaration of arrays
StudentMarkTest1 = array.array ("i", range(Constnostudents))
StudentMarktest2 = array.array ("i", range(Constnostudents))

for Counter in range(0, Constnostudents):
    StudentName.append (input("Please enter name of student"))
    StudentGender.append (input("Please enter your gender"))
    while (StudentName[Counter] !="M" or StudentName[Counter] != "F"):
        input("Please enter valid ")

    StudentMarkTest1[Counter] = int(input("Please enter marks for test 1"))
    StudentMarktest2[Counter] = int(input("Please enter marks for test 2"))

print(StudentName)
print(StudentGender)
print(StudentMarkTest1)
print(StudentMarktest2)

If you are trying to check if the gender they provided is a valid one, you are giving the wrong value to the while loop.如果您试图检查他们提供的性别是否有效,那么您就是在为while循环提供错误的值。 You need to give the "StudentGender" variable and not the "StudentName" variable.您需要提供“StudentGender”变量而不是“StudentName”变量。 Also you are not reassigning the " StudentGender", so it doesn't matter if they are going to provide a valid answer.此外,您不会重新分配“StudentGender”,因此他们是否要提供有效答案并不重要。 The loop will continue to run...循环将继续运行......

You should do:你应该做:

while (StudentGender[Counter] !="M" and StudentGender[Counter] != "F"):
       StudentGender[Counter] = input("Please enter valid gender").upper()

I also added .upper() to the gender.我还在性别中添加了.upper()

For the reason of the "and" instead of "or", look at the comments in your question.由于“和”而不是“或”的原因,请查看您问题中的评论。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM