python - 无限循环

标签 python

为什么当输入正确的输入(0 到 100 之间的数字)时这个 while 循环没有结束

grade = 110
invalid_input = 1
while grade< 0 or grade> 100:
    if invalid_input >=2:
        print "This is an invalid entry"
        print "Please enter a number between 0 and 100"
    grade= raw_input("Please enter your marks for Maths : ")
    invalid_input +=1

我输入的是数字还是文本(这是无效输入,请输入 0 到 100 之间的数字 有谁知道哪里出了问题?

最佳答案

您的成绩 应转换为 int。否则,由于它是一个字符串,while 条件将始终满足。

此外,您可以同样轻松地(也许更干净地)为 invalid_input 使用 bool 值:

invalid_input = True
while invalid_input:
    grade = int(raw_input("enter data"))
    if grade >= 0 and grade <= 100:
        invalid_input = False
    else:
        print "Please try again"

关于python - 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14086238/

相关文章:

python - 在 Python 中查找字符串下方(以及字符串之间)的单词

python - 如何在应用于数据框的函数中使用行索引和单元格值?

python - Python 正则表达式是否支持类似 Perl's\G 的东西?

Python列表: how to make it ordered and get rid of duplicates

python - 如何结合.shift()在dataframe中进行查询

python - Matplotlib:将图形向右移动

python - 有什么方法可以在使用 python panda 时显示特定的单元格值以及标题和列值

python - 无法到达类参数中的函数

python - 使用 Djoser 和 Django Rest Framework 激活帐户

python - 如何使用 pandas 将一列 csv 读取为 dtype 列表?