首页 > 解决方案 > 使用带有 and 条件的 while 循环输入两个值之间的数字

问题描述

我正在尝试使用 while 循环在 python 中的两个数字之间输入一个输入,以便它不断询问问题,直到满足两个条件,但是当我运行代码时它一直跳过这个。

NumOfStudents=0

while NumOfStudents > 35 and NumOfStudents < 28:
  NumOfStudents = int(input("Please enter the number of students:"))

为什么 and 不能在这里工作,我应该使用什么来代替?

标签: pythonwhile-loop

解决方案


它不起作用,因为您的代码没有意义。您在 while 循环中要求一个必须大于 35 且小于 28 的数字,这是不可能的。

如果你想让它工作,while 循环的条件应该改变。

此外,如果您将 NumOfStudents 变量初始化为 0,您将永远不会进入 while 循环。

如果您执行以下操作,它可能会起作用:

    NumOfStudents=int(input("Please enter the number of students:"))

    while NumOfStudents < 35 and NumOfStudents > 28:
      NumOfStudents = int(input("Please enter the number of students:"))

推荐阅读