I have a code like that,
i = 0
l1 = ['a','b','c']
while(i < len(l1)):
if i + 2 < len(l1):
if l1[i + 2] == 'c':
print("ok")
else:
print("None,Error!")
else:
print("None,Error!")
i += 1
As you can see, in the else part, print("None,Error!") are used in two times. In practice, they are very long but totally same so I want to merge them to make them simple.However, I need to check if i+2 is out of list bound, so I cannot rewrite it to
if i+2 < len(l1) and l1[i + 2] == 'c':
Is there any idea can solve this problem?
>Solution :
As Phu Ngo mentions, we can take advantage of short circuiting to write
i = 0
l1 = ['a','b','c']
while(i < len(l1)):
if i + 2 < len(l1) and l1[i + 2]=='c':
print("ok")
else:
print("None,Error!")
i+=1
If i+2<len(l1) is false, then the expression l1[i + 2]=='c' is never evaluated, which means that no error is raised.
Another solution that can be considered here is a try/except clause.
i = 0
l1 = ['a','b','c']
while(i < len(l1)):
try:
if l1[i+2]=='c':
print("ok")
else:
raise ValueError
except Exception:
print("None,Error!")
i+=1
Both result in the printouts
ok
None,Error!
None,Error!