2016-10-02 85 views
0

我正在构建一个简单的程序,以便为我的租赁属性预先筛选租户。程序询问他们一系列问题 - 其中一些问题需要一个“是”或“否”的答案,这将是一个布尔(真/假)。使用python输入布尔值

问题是,无论您为布尔输入回答什么,它都会记录为“1”。

我使用本地sqlite3的来存储数据,下面的代码:

def enter_dynamic_data(): 
    fname = input("First Name? ") 
    lname = input("Last Name? ") 
    email = input("Email? ") 
    phone = input("Phone? ") 
    criminal = bool(input("Have you ever been convicted of a crime? ")) 
    evicted = bool(input("Have you ever been evicted? ")) 
    income = bool(input("Do you have verifiable income of at least 3x the rent amount? ")) 
    ref = bool(input("Do you have good rental references? ")) 

    c.execute("INSERT INTO tenant_screening (firstname, lastname, email, phone, criminal, evicted, income, ref) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (fname, lname, email, phone, criminal, evicted, income, ref)) 
+0

这是因为bool()函数评估一切为真(1),除了像空列表/元组,空,假或空字符串的东西。说布尔(“任何”)总是评估为真,因为有什么。 – Nf4r

+0

几乎重复的是,sqllite3布尔被存储为0,1。* SQLite没有单独的布尔存储类*。 [doc](http://www.sqlite.org/datatype3.html)仅供参考 – idjaw

+0

就像:answer = input()。lower()==“yes”;.您还可以执行其他检查:answer = int(input())> 100;等等.. – dinomoth

回答

0

如果输入不是无,则以布尔值包装输入将始终返回True。相反,你可以这样做:

response = False if raw_input("The yesno question? ").lower() == 'no' else True 
0

在Python任何非空字符串被认为是True所以无论用户的输入被输入的所有非空字符串转换为布尔值时用户将为True

>>> bool('true') 
True 
>>> bool('false') 
True 
>>> bool('') 
False 

所以你需要比较用户对一组代表True值的输入的值,例如

YES_VALUES = {'y', 'yes', 'ok'} 

criminal = input("Have you ever been convicted of a crime? ").lower() in YES_VALUES 

此用户的输入转换为小写,然后检查该值是否在设置YES_VALUESx in y的结果已经是布尔值,因此不需要通过bool进行明确的转换。