【问题标题】:How to solve python while statement error with string? [duplicate]如何用字符串解决python while语句错误? [复制]
【发布时间】: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 是一个真值。

标签: python boolean operators


【解决方案1】:

我认为您的概念很好,我看到了代码并且您尝试做的事情是合乎逻辑的。您误会的是逻辑运算符在 Python 中的工作原理。无论如何,我在您的代码中看到三个主要错误,其中一个使您相信问题是检查字符串数据类型(但不是问题所在。

第一个和第二个问题让你相信程序无法检查用户输入是否为字符串(“确定 int 值没问题,但字符串值不起作用。”)

第一期

真假值

response == int or float

这将永远是True,因为or float。 因为即使 First 检查是否为 False,or float 也在检查浮点类型是否为真,并且始终为真!

print(bool(float))
# >>> True
if float:
    print("Floating....")
else:
    print('....')
# >>> Floating....

# Infinite Loops, these are all equal
while float:
    ....
white bool(float):
    ...
white True: 
    ....
   

第二期

了解条件语句and or 的工作原理。

又来了:

 response == int or float

你应该使用:

 while response == int or response == float:

在 Python(以及我相信的大多数语言)中,您不能像英语那样连接条件运算符,该行可以更清楚地写成这样:

(response == int) or (float)  # 1 version
(response == int) or (bool(float) == True) # Converting float to 

从逻辑上讲,我可以看出你想说:

'检查值是整数还是浮点数'

但是你的代码是怎么写的

'检查值是否为整数,如果不是则检查浮点数是否为真值'*

第三期

ì输入的数据类型始终是字符串!

然后该函数从输入中读取一行,将其转换为字符串

我想你没有注意到这个,因为前面的2个错误让你认为程序无法检查值何时是字符串。

现在您看到问题实际上是检查值是 int 还是 float,而不是 string。

解决方案

这将是我的解决方案,与其做太多的嵌套条件检查,不如尝试一下,除非以 “Ask forgiveness not permission” - explain 样式阻塞。

  # Input Checks
response = input("\nWhere raw data located(folder)? : ")
    print(response)
    print(type(response))  # Check the type, you will see is always a string
    while True:
        try:
            float(response) # Not need to check for a int, float checks for both (and int too it will truncate the float)
        except ValueError:
            print("String Found!!!")
            break
        else:
            print('Float or int found, programs keeps running..')
            pass

关于真实的价值观

来源 --> What is Truthy and Falsy? How is it different from True and False?

所有值都被认为是“真实的”,除了以下是“虚假的”:

  • None
  • False
  • 0
  • 0.0
  • 0j
  • decimal.Decimal(0)
  • fraction.Fraction(0, 1)
  • [] - 一个空的list
  • {} - 一个空的dict
  • () - 一个空的tuple
  • '' - 一个空的str
  • b'' - 一个空的bytes
  • set() - 一个空的set
  • 一个空的range,比如range(0)
  • 对象
    • obj.__bool__() 返回False
    • obj.__len__() 返回0

“真实”值将满足ifwhile 语句执行的检查。我们使用“truthy”和“falsy”来区分boolTrueFalse

[真值测试](https://docs.python.org/3/library/stdtypes.html#truth-value-t

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 感谢您的评论。我明白你的意思,这很好。但是当我尝试这段代码时,循环永远不会结束。我不明白为什么会这样......
    • 因为下一次,您将输入分配给welcome_input。相反,将其重新分配给response。 @BellaLee
    • 谢谢你,我刚刚发现系统认为1是一个字符串。所以我认为系统允许每个值,即使它是一个数字。这是正常的吗?有什么好的方法可以解决这个问题吗?非常感谢
    猜你喜欢
    • 2021-08-08
    • 2020-03-17
    • 2011-10-09
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    相关资源
    最近更新 更多