2017-08-02 191 views
0
#room B register 
#matrix method 
roomB = [[],[]]  

我打算在這裏只輸入3個單位roomB =如何設置python列表上的輸入限制3

def func(): 
    row = int(input("Choose 0 or 1:")) 
    if (row == 0):     # ROW 0 IS FOR HOUSE 1: 
      name = input("Enter your room name: ") 
      print("Enter M or N")  #M for master room 
      room_type = input("")   #N for normal room 
      for u in roomB:  #3 units in roomB[0] 
       if(len(u)<3): 
       if (room_type == "M"): 
        return roomB[0].append([room_type,name,140]) 
       if (room_type == "N"): 
        return roomB[0].append([room_type,name,140]) 
+0

你的問題是什麼?你收到任何錯誤或意外的行爲? –

+0

你期望輸出什麼? – Gahan

+0

我沒有收到任何錯誤,但我希望我的輸出在我的列表中只插入3個單位你有任何建議我應該改變嗎? – Jordan

回答

0
roomB = [[],[]] 

def update(row): # takes sublist as argument 
    if len(roomB[row]) < 3: # checks if sublist length is less than 3 
     name = input("Enter your name: ") 
     room_type = input("Enter room type : M (master room) or N (normal room) : ").lower() 
     roomB[row].append([room_type,name,140]) 
     return "your room no. is {} at row {}".format(roomB[row].index([room_type,name,140]) + 1, row) # returns string stating status 


def func(): 
    if len(roomB[0]) < 3 and len(roomB[1]) < 3: # ask for prompt only if space available in both sublist 
     row = int(input("Choose 0 or 1: ")) # allow to select row 
     return update(row) 
    elif len(roomB[0]) >= 3 and len(roomB[1]) < 3: # selects default sublist if no space on other sublist 
     print("No room available at 0 , selected 1 ") 
     return update(1) # returns string stating status 
    elif len(roomB[0]) < 3 and len(roomB[1]) >= 3: # selects default sublist if no space on other sublist 
     print("No room available at 1 , selected 0 ") 
     return update(0) 
    else: # in case any error occurs it goes here 
     print("Errrr.......") 
     print("room stat....: ", roomB) 

while len(roomB[0]) <= 3 or len(roomB[1]) <= 3: # loop will flow if length of both sublist is greater than or equals to 3 
    if len(roomB[0]) != 0 or len(roomB[1]) != 0: # won't ask for confirmation if all all lists are empty (skips prompts for initial) 
     cond = input("do you want to continue?(Y/N) ").lower() 
     if cond == "n": 
      break # break the loop if pressed n or N otherwise continue to execute 
    elif len(roomB[0]) >= 3 and len(roomB[1]) >= 3: # error message to print if no space left in sublists 
     print("No room available.. Sorry for inconvinience.") 
    print(func()) 
+0

嗨謝謝你的解決方案btw我可以問爲什麼我們應該使用格式而不是追加?而我想要的房間只有1個主臥室和2個正常的臥室 – Jordan

+0

我已經使用append。 append只會將元素追加到列表中,因此當您編寫'return list.append()'時,它(函數)將返回None。格式是在python中的字符串格式。因爲我已經寫它返回字符串 – Gahan

+0

你可以upvote和接受作爲答案,如果有幫助 – Gahan