猿问

我希望它在不是 0 或 1 时给我错误

#!/usr/bin/python


def open_doors(state):

    (ld, rd, li, ri, lo, ro, cl, ml, gs) = state


    if not(ld == 0 or rd == 0 or li == 0 or ri == 0 and lo == 0 or ro == 0 or cl == 0 or ml == 0):

      raise ValueError("Error: A state is not specified or invalid entry")


    if not(ld == 1 or rd == 1 or li == 1 or ri == 1 and lo == 1 or ro == 1 or cl == 1 or ml == 1):

      raise ValueError("Error: A state is not specified or invalid entry")


    leftDoor = (ld or li or lo)

    rightDoor = (rd or ri or ro)

    if (li and cl):

      leftDoor = 0

    if (ri and cl):

      rightDoor = 0


    if leftDoor and rightDoor and not ml and gs == 'P':

      print("left door and right door open")

    elif leftDoor and not ml and gs == 'P':

      print("open left door")

    elif rightDoor and not ml and gs == 'P':

      print("open right door")

    else:

      print("both doors stay closed")   


open_doors([0,0,1,6,0,0,1,0,'2'])

如果未指定每个状态,开关和锁不是 0 或 1 或 gs 不是 ('P' 'R', 'N', '2', '3' 'D') 之一,则引发 ValueError


繁星点点滴滴
浏览 134回答 1
1回答

慕容森

我会做if any((i != 0 and i != 1) for i in state):  raise ValueError("Error: A state is not specified or invalid entry")这是简短而简洁的。它甚至可以更改为valid = set((0, 1))if any(i not in valid for i in state):  raise ValueError("Error: A state is not specified or invalid entry")我不确定这是否是更好的性能或可读性。
随时随地看视频慕课网APP

相关分类

Python
我要回答