【问题标题】:converting a string into false Boolean value将字符串转换为 false 布尔值
【发布时间】:2020-01-07 03:57:59
【问题描述】:

我想知道如何将字符串值转换为 False 布尔值,因为每次运行代码时它都会返回 True 值。

high_income = input(“Do you have a high income?:”)
credit = input(“Do you have a credit line?”)
If high_income and credit: 
      Print(“eligible for loan”)
else:
     print(“not eligible”)

【问题讨论】:

  • 输入总是返回字符串,非空字符串总是给出True - 你应该比较ie。 high_income.lower() == 'yes' and credit.lower() == "yes"

标签: python logical-operators


【解决方案1】:

if 语句评估你给它的布尔值 (bool) 并根据它的真值进行操作。如果字符串被评估为布尔值,则空字符串''False,任何非空字符串为True

因此,无论您输入什么,它的计算结果始终为True,除非您什么都不输入。

你想要的是评估一个特定的字符串,所以你有两个选择;第一种是直接检查表示“真”的字符串:

if high_income.lower() in ['yes', 'y', 'true']:

注意.lower() 会导致答案转换为小写,所以'Yes' 也是True

第二个是评估用户输入的内容并使用该值:

if eval(high_income):

但这通常不是一个好主意,因为无论用户类型如何,都会被评估为有效的 Python 表达式,这可能会导致意外结果甚至不安全的情况。此外,如果用户键入2+2,那也是True,因为它的计算结果是整数值4,任何不是0 的整数值总是True

【讨论】:

    【解决方案2】:
    high_income = input("Do you have a high income?:")    
    credit = input("Do you have a credit line?")   
    if high_income == 'yes' and credit == 'yes':  
    
          print("ligible for loan")
    else:
    
         print("not eligible")
    #output
    #Do you have a high income?:yes
    #Do you have a credit line?yes
    #ligible for loan
    

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 2016-04-05
      • 2011-12-28
      • 2018-09-07
      • 1970-01-01
      • 2012-03-10
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多