Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid write similar code multiple times in this situation?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading