开发者

A simple IF statement in python

开发者 https://www.devze.com 2023-03-19 18:15 出处:网络
I\'m having trouble getting an \"Else\" statement to work. My code looks like this so far: roomNumber = (input(\"Enter the room number: \"))

I'm having trouble getting an "Else" statement to work.

My code looks like this so far:

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'])

So when i do a positive search and get multiple matches in my text file, i get well organised results.

However, i'm trying to get it to tell me if invalid input data is entered and re-ask for the room number until the correct data is input.

I 开发者_如何学运维tried using an "Else" statement about the "Yield(s)" but it wont accept it. Any ideas?


Python blocks are delineated by indentation so the "else:" (note lowercase and with a colon to indicate the start of a block) should be at the same indent level as the if statement.

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.

But I suspect you don't really want to use an else clause anyway, where would you go from there? This looks an awful lot like an assignment so I'm not going to post an exact solution.


You can do it like this:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消