减少Python中模拟do..while循环的频率

2024-06-01 22:53:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我意识到我正在编写大量重复的代码,这些代码围绕着一个模拟的do..while循环来验证用户输入。你知道吗

有没有办法减少这种重复编码的频率?你知道吗

例如:

validity = False
while validity == False:        
    choice = input('Enter 1 --> , 2 --> , 3 --> ....')
    if choice == '1':
        validity = True
        stuff1()
    if choice == '2':
        validity = True
        stuff2()
    if choice == '3':
        validity = True
        stuff3()
    else:
        print('Invalid Input.')

Tags: 代码用户falsetrue编码inputifdo
3条回答

也可以删除validity并使用break语句:

while True:
    choice = input('Enter 1  > , 2  > , 3  > ....')
    if choice in (1, 2, 3):
        stuff()
        break
    else:
        print('Invalid Input.')

您可以使用set

for choice in {1, 2, 3}:
    validity = True
    stuff()

tuple

for choice in (1, 2, 3):
    validity = True
    stuff()

也不是做:

while validity == False:

进行错误检查:

while not validity:

假设你的意思是:

validity = False
while validity == False:        
    choice = input('Enter 1  > , 2  > , 3  > ....')
    if choice == '1':
        validity = True
        stuff1()
    if choice == '2':
        validity = True
        stuff2()
    if choice == '3':
        validity = True
        stuff3()
    else:
        print('Invalid Input.')

然后你可以做:

actions = { '1': stuff1, '2': stuff2, '3': stuff3 }
invalid = lambda: print('Invalid Input.')
while True:
    choice = input('Enter 1  > , 2  > , 3  > ....')
    action = actions.get(choice, invalid)
    action()
    if action is not invalid:
        break

您可以将其放入可重用函数中:

def act(actions):
    while True:
        val = input('Enter 1  > %d: '%len(actions))
        try:
            choice = int(val)-1
        except ValueError:
            choice = -1
        if not 0 <= choice < len(actions): 
            print('Invalid Input.')
        else:
            break
    actions[choice]()

所以你只需要:

act([stuff1, stuff2, stuff3])

例如:

>>> act([lambda: print("chose 1"), lambda: print("chose 2"), lambda: print("chose 3")])
Enter 1  > 3: 4
Invalid Input.
Enter 1  > 3: 3
chose 3

Edit:更新以反映python3input()(返回字符串)的使用,并显示其工作情况

相关问题 更多 >