jeudi 16 août 2018

Shortening an if, elif, elif else clause

I am making a program that checks when the next train leaves. For that, it takes the departure times from a website and stores them in arrays(times_luz and times_hitz).

However, the API sometimes doesn't have any Information, so there's no data in the array which, later in the code, leads to an error, Therefore I thought this would be a good Idea:

if times_hitz and times_luz:
   Code to be executed if both contain values

elif times_luz:
   Code to be executed if only times_luz contains values

elif times_hitz:
   Code to be executed if only times_hitz contains values

else 
   print("No content available")
   sys.exit()

This would technically work, but the code is currently about 10 lines long so I would have to Copy & Paste that Code 2 times with only slight changes. This would lead to about 80 lines of code and would look pretty ugly. Is there any better way of doing this?

Aucun commentaire:

Enregistrer un commentaire