2011-07-13 107 views
-4

我無法使「Else」語句正常工作。python中的簡單IF語句

我的代碼看起來像這樣至今:

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」關於「Yield(s)」的說法,但它不會接受它。 任何想法?

+0

我認爲你需要'else'來代替'for'循環。你真的想在循環的第一次迭代之後關閉文件嗎? – DrTyrsa

+2

'否則:'應該和'if ..:'在同一級別 - 也許你可以發佈除了上述內容外沒有任何工作的代碼。 – Soren

回答

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

的Python塊被縮進因此,「別人:」劃定(注意小寫字母和一個冒號指示塊的開始)應在同一作爲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子句,你會從哪裏去?這看起來非常像一個任務,所以我不打算髮佈一個確切的解決方案。