python - 如何用字符串解决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 : ")
解决方案
您无法将 astring
与数据类型进行比较。它永远是假的。此外,int or float
后半部分将评估为True
。
您必须使用type
来检查参数的数据类型
response = input("\nWhere raw data located(folder)? : ")
while type(response) not in [int, float]:
推荐阅读
- sql - 如何删除空字符串
- python - 如何使用方法打印文件名列表
- java - 如何将 Keycloak 7 与 Spring Boot 2 集成
- python - 返回 %ROWTYPE 的 Python cx_Oracle 调用函数
- html - 使用 MSO 前缀调整图像属性
- php - 为什么我的提交按钮调用php函数失败?
- c# - 返回具有分配的所有子项的新列表的函数 VS 返回该列表的子项但未分配的函数
- google-cloud-platform - 如何将 Cloud Endpoints 配置到现有的 Spring Boot 应用程序(在 App Engine 上运行)?
- java - 使用 Part 类 jsp 编译 FileUpload servlet 时找不到符号
- scala - Spark 提交作业在本地模式下失败且没有错误