简体   繁体   English

如何正确执行if语句

[英]How to implement the if statement properly

I have a snip of code listed here.我在这里列出了一段代码。 Basically is a database containing motel room numbers.基本上是一个包含汽车旅馆房间号的数据库。 There are 5 rooms in the data base.数据库中有 5 个房间。 Some are dirty and some are clean.有些很脏,有些很干净。 What I want to do is list all of the rooms into the listbox whether they are dirty or not.我想要做的是将所有房间列出到列表框中,无论它们是否脏。 I'm having trouble figuring out the correct if statement to use so that I will list all rooms and print '--Dirty' beside the ones that are dirty.我无法确定要使用的正确 if 语句,以便列出所有房间并在脏的房间旁边打印“--Dirty”。

def viewrooms():
rooms = Toplevel()
rooms.title('Room List')
rooms.geometry("800x900+550+50")

roomlb = Listbox(rooms, height=40, width=30, font="12")
roomlb.place(x=300, y=20)

conn = sqlite3.connect('roominventory.db')
c = conn.cursor()
c.execute("SELECT * FROM rooms")
records = c.fetchall()

for record in records:
    if record[4]=="N":
         room = str(record[0:2])
         status = "--Dirty"

    roomlb.insert(END, room + status)

First thing I notice is that you don't reset the status variable so all the rooms after the first dirty one will be listed as dirty.我注意到的第一件事是您没有重置状态变量,因此第一个脏房间之后的所有房间都将被列为脏房间。 The second thing is that if the first room is clean the status variable will not exist so roomlb.insert will fail also as noted above room will also be undefined.第二件事是,如果第一个房间是干净的,则状态变量将不存在,因此 roomlb.insert 也会失败,如上所述,房间也将未定义。

These thre problems can be overcome with a two-line addition to your code:可以通过在代码中添加两行代码来克服这些问题:

...
for record in records:
    room = ...
    status = ""
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM