Tips for Python

Ignacio Ruiz
2 min readMay 24, 2021

The one about the try and except!

Hey! welcome back! so, today we will be looking at a really cool thing that you may not know python can do and I believe that it can be super helpful in your next coding project.

Today, we will check out the try: and except:items. If you have done some web scraping in python you will probably be familiar with them. Here we will explore other possible applications.

When it comes to try: and except: you can think of them as logic gates, similar to an if but in this case, what you are dealing with is system errors.

When you run try: you are telling Python to run whatever you coded inside it; while the code runs, as long as there are no “errors” or everything is “true” the code will not be interrupted. When it comes to excetp:, whenever the code that is in try: raises an error, you can code how you want python to deal with it.

Let’s begin! To start we can use it as an if statement in our function. Here, the list “items” contains numbers but has a rouge string in it. If we created a function raising everything to the power of 2, it will return an error due to the fact that strings are unable to be treated like int.

But, let’s say, you don’t know what your input will be but you only care about the numbers? Then we can use try: and except: as our logic gates.

Here we are telling python “ For every item in items try raising it to the power of 2. If that raises an error pass said item. ” And now we were able to raise the list to the power of 2 and avoided the code-breaking due to the fact that we told python to pass any error that it was raised.

There are many ways that we can use these items where you can choose whichever error to deal with or if you’d like to code to break and raise a specific message! you can go ahead and give it a try!

--

--