Where do I put common code for if and elif?
For the example below:
if a == 100:
# Five lines of code
elif a == 200:
# Five lines of code
Five lines of code is common and repeating how can I avoid it? I know about putting it a function
or
if a == 100 or a == 200:
# 开发者_开发技巧Five lines of code
if a == 100:
# Do something
elif a == 200:
# Do something
Any other cleaner solution?
Alternative (1): put your 5 lines in a function, and just call it
Alternative (2)
if a in (100, 200):
# five lines of code
if a == 100:
# ...
else:
# ...
A little less verbose than your code
Remember that with functions, you can have local functions with a closure. This means you can avoid passing repetitive arguments and still modify locals. (Just be careful with assignments in that local function. Also see the nonlocal
keyword in Python 3.)
def some_func(a):
L = []
def append():
L.append(a) # for the sake of example
#...
if a == 100:
append()
#...
elif a == 200:
append()
#...
def five_lines(arg):
...
if a in [100,200]:
five_lines(i)
精彩评论