Does someone knows why is executing both the If and ELSE statement? Please check my python codes

Hello Y'all..
Hope someone can #help with this question:
I'm plotting a pandas dataframe, where I created a try / except block to create a PDF file. So, if the IF conditional period_fails is not empty, the ELSE statement runs and create a pdf, no problem with that.  if the IF conditional period_fail is empty it raise a ValueError and execute the except ValueError block, great..., but for some reason, still executing the else statement and creating an empty PDF.
Does someone knows why is executing both the If and ELSE statement?
 
print(count) # datafrma to be plotted

-F
2018-09-03 19
2018-09-04 8
2018-12-07 6

print(count.dtypes)
-F int64
dtype: object
#------------------------
try:
with PdfPages(os.path.join(my_out_path, ("{0}_{1}" + ".pdf").format(fname, last_month))) as export_pdf:
if period_fail.empty:
raise ValueError
else:
count.plot(kind='bar', color='red', legend=None, title='Date / Count')
plt.xlabel('Date')
plt.ylabel('Count')
plt.xticks(rotation=20)
export_pdf.savefig() # to save the plot
export_pdf.close() # close the created pdf

except ValueError:
print('No failure processes between {} and {}'.format(last_month, first))
sys.exit(100)

except Exception as e:
print(e)

 
 
You already invited:

Nora

Upvotes from: Benny

The PDF is being created/opened in the `with` statement, and then gets closed automatically when that block is exited, leaving behind a blank file. You'll want to put your `empty` check earlier to avoid that.

If you wanna answer this question please Login or Register