I have created if-else statements within my functions to check if certain conditions are met. However, I need to convert it try-except statement since the app I am working on is set up so that when a condition is met, it creates log info statements and when it is not met it creates log error statements. Currently my code looks like:
if (conditon1 == 1):
print('Everything is good')
else:
orig_diff = list(set(sheetnames).difference(file.sheet_names))
new_diff = list(set(file.sheet_names).difference(sheetnames))
if len(orig_diff) != 0:
print("{} cond1 not met".format(','.join(orig_diff)))
if len(new_diff) != 0:
print("{} cond2 not met".format(','.join(new_diff)))
I want it to be so that if the if-condition is met then it will print the info statement. But if it is not met, then the else statements will be executed. Something like:
try:
return bool(condition1 == 1)
print('Everything is good')
except:
orig_diff = list(set(sheetnames).difference(file.sheet_names))
new_diff = list(set(file.sheet_names).difference(sheetnames))
if len(orig_diff) != 0:
print("{} cond1 not met".format(','.join(orig_diff)))
if len(new_diff) != 0:
print("{} cond2 not met".format(','.join(new_diff)))
But, I can't seem to get this to work and even when the condition is not met it returns 'Everything is good'.
I think this would be a good way of doing it - if cond1 equals 1, it'll go down the happy path , the else
block. If it doesn't (the assert
ion fails, so the condition isn't met), it does what you wanted it to - prints an error message.
try:
assert(condition1 == 1)
except AssertionError:
orig_diff = list(set(sheetnames).difference(file.sheet_names))
new_diff = list(set(file.sheet_names).difference(sheetnames))
if len(orig_diff) != 0:
print("{} cond1 not met".format(','.join(orig_diff)))
if len(new_diff) != 0:
print("{} cond2 not met".format(','.join(new_diff)))
else:
print("Everything's fine!")
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.