如何使用python 3在列表上设置输入限制

时间:2017-08-02 04:49:43

标签: list python-3.x

#room B register
#matrix method
roomB = [[],[]]    

我打算在这里只输入3个单位roomB = [[],[]]如果第一个单位已满,系统应该建议另一个单位。

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

1 个答案:

答案 0 :(得分: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())