【发布时间】:2021-10-22 04:15:42
【问题描述】:
这是我的解释。 此代码是用户输入的“字符串”值。
对于这段代码中的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,则显示错误消息)并且效果很好。 但是对于'string'值,它不起作用。
我使用 while 语句确定字符串值的代码是否错误?
用于确定int 值可以,但字符串值不起作用。
我很困惑,因为我认为我没有犯任何错误。
有人可以帮帮我吗?
response = input("\nplease enter the value : ")
while response == int or float:
print(" Enter the value ")
response = input("\nplease enter the value : ")
【问题讨论】:
-
您将
response与数据类型进行比较。response == int or float永远不会是真的。你应该做while type(response) not in [int, float]。input返回一个字符串。并且string数据类型不在数据类型列表中 -
@Sujay
réponse == int or float总是为真,因为float是一个真值。