我意识到我正在编写大量重复的代码,这些代码围绕一个模拟的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.')
答案 0 :(得分:1)
您可以使用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:
答案 1 :(得分:1)
您也可以删除validity
并使用break
声明:
while True:
choice = input('Enter 1 --> , 2 --> , 3 --> ....')
if choice in (1, 2, 3):
stuff()
break
else:
print('Invalid Input.')
答案 2 :(得分:0)
假设你的意思是:
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
编辑:更新以反映使用python3 input()
,它返回字符串,并显示它的工作原理