首页 > 解决方案 > 如何用字符串解决python while语句错误?

问题描述

这是我的解释。此代码是用户输入“字符串”值的内容。

对于这段代码中的 while 语句,我想编写一个类似“如果输入值不是字符串值,则打印消息,直到程序获取字符串值”的代码。

我尝试了很多东西while not response == str:, while not response == str(response):, while response == int or float:, while response == int and float:,while response == int or response == float等等。所有这些东西都没有达到我的目的。

其中一些允许所有类型的值并且没有执行循环。其他人只是一次又一次地显示循环,即使值是一个字符串。

我还编写了其他代码来确定 int 值(如果输入不是 int,则显示错误消息)并且效果很好。但是对于“字符串”值,它不起作用。

我用 while 语句确定字符串值的代码是否错误?
确定int值是可以的,但字符串值不起作用。

我很困惑,因为我认为我没有犯任何错误。
有人可以帮我吗?

    response = input("\nplease enter the value : ")

    while response == int or float:                                                                                            

        print(" Enter the value ")
        
   
        response = input("\nplease enter the value : ")

标签: pythonbooleanoperators

解决方案


您无法将 astring与数据类型进行比较。它永远是假的。此外,int or float后半部分将评估为True

您必须使用type来检查参数的数据类型

response = input("\nWhere raw data located(folder)? : ")
while type(response) not in [int, float]:

推荐阅读