我想知道如何获取字符串值以将其转换为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”)
if
语句评估您为布尔值(bool
)提供的内容,并根据其真实值进行操作。如果将字符串评估为布尔值,则空字符串''
为False
,任何非空字符串为True
。
因此,无论您输入什么,它将始终计算为True
,除非您什么都不输入。
您想要的是评估一个特定的字符串,因此您有两个选择;第一种是直接检查表示“ True”的字符串:
if high_income.lower() in ['yes', 'y', 'true']:
请注意,.lower()
使答案转换为小写,因此'Yes'
也是True
。
第二个是评估用户键入的内容并使用该值:
if eval(high_income):
但这通常不是一个好主意,因为无论哪种用户类型,都将其视为有效的Python表达式,这可能会导致意外结果甚至不安全的情况。另外,如果用户键入2+2
,也就是True
,因为它的计算结果为4
的整数值,任何非0
的整数值始终为True
。
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