简体   繁体   中英

Python: need to stop running code, if a condition is met/not met

I wrote a python code to check the validity of a string as per a specific MOD11 algorithm, but wanted to further check with regex if the string is in the correct structure to begin with.

TIN = '5562000'

import re
x = re.search("\d{7}(\d|K){1}", TIN)
if x != 'None':
    print ('Structure Valid')
    
    check = (int(TIN[0])*8) + (int(TIN[1])*7) + (int(TIN[2])*6) + (int(TIN[3])*5) + (int(TIN[4])*4) + (int(TIN[5])*3) + (int(TIN[6])*2)

    y = check / 11

    z = "{:.0f}".format(y)

    print(z, TIN[7])

    print((TIN[7]) is str(z))

    if ((TIN[7]) == str(z)) & (str(z) != '0'):
        print('Valid TIN')
    elif ((TIN[7]) == 'K') & (str(z) == '10'):
        print('Valid TIN')
    elif (TIN[7] == '0') & (str(z) == '11'):
        print('Valid TIN')
    else:
        print('Invalid TIN!')   

else:
    print('Invalid Structure')

When the structure is valid, ie number of characters is correct, all works fine. However, if there's a character missing in the TIN variable, I get this error:

    print(z, TIN[7])
IndexError: string index out of range

So, I need a way to NOT run this portion of the code, if TIN is not in the correct structure:


y = check / 11

z = "{:.0f}".format(y)

print(z, TIN[7])

print((TIN[7]) is str(z))

if ((TIN[7]) == str(z)) & (str(z) != '0'):
    print('Valid TIN')
elif ((TIN[7]) == 'K') & (str(z) == '10'):
    print('Valid TIN')
elif (TIN[7] == '0') & (str(z) == '11'):
    print('Valid TIN')
else:
    print('Invalid TIN!')

I tried while and for loops with the break function and sys.exit, also tried indentation, but I'm not that good yet to make it work. Any ideas on how to make this work?

The key mistake is your comparison of the regex result:

if x != 'None':

compares x with the string "None" , which is different from the None keyword:

>>> None == "None"
False

You want your check to be:

if x is not None:

then, everything should work.

Edit: Keep in mind that re.search allows for additional characters before and after the regex match. I think you might not want this here, so you might want to use re.fullmatch instead.

You can use

try:
    print(z, TIN[7])
except Exception as e:
    print(e)
    #further code

It will try to perform the block inside try . If it executes with no errors then it will continue further without considering except part. If there is any problem in that block, it will execute the block inside except and store the error in e .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM