python中的简单IF语句

时间:2011-07-13 09:07:46

标签: python

我无法获得“Else”声明。

到目前为止,我的代码看起来像这样:

roomNumber = (input("Enter the room number: "))

def find_details(id2find):
    rb_text = open('roombookings2.txt', 'r')
    for line in rb_text:
        s = {}
        (s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
        if id2find == (s['Room']):
            yield(s)
        rb_text.close()


for room in find_details(roomNumber):
    print("Date: " + room['Date'])
    print("Room: " + room['Room'])
    print("Course: " + room['Course'])
    print("Stage: " + room['Stage'])

因此,当我进行正面搜索并在我的文本文件中获得多个匹配时,我会得到组织良好的结果。

但是,我试图告诉我输入的输入数据是否无效,并在输入正确的数据之前重新询问房间号。

我尝试使用关于“收益率”的“Else”声明,但它不接受它。 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

Python块由缩进描述,因此“else:”(注意小写并用冒号表示块的开头)应该与if语句处于相同的缩进级别。

def find_details(id2find):
    rb_text = open('roombookings2.txt', 'r')
    for line in rb_text:
        s = {}
        (s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
        if id2find == (s['Room']):
            yield(s)
        else:
            print "this print will execute if d2find != (s['Room'])"
        # ... also see DrTyrsa's comment on you question.

但我怀疑你真的不想使用else条款,你会从那里去哪里?这看起来很像一个任务,所以我不打算发布一个确切的解决方案。

答案 1 :(得分:0)

你可以这样做:

def find_details(id2find):
    found = False
    with open('roombookings2.txt', 'r') as rb_text:
        for line in rb_text:
            s = {}
            (s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
            if id2find == s['Room']:
                found = True
                yield(s)
    if not found:
        raise ValueError("No such room number!")

while True:
    roomNumber = (input("Enter the room number: "))
    try:
        for room in find_details(roomNumber):
            print("Date: " + room['Date'])
            print("Room: " + room['Room'])
            print("Course: " + room['Course'])
            print("Stage: " + room['Stage'])
        break
    except ValueError as e:
        print str(e)