DEV Community

Cover image for Learning Python-Basic course: Day 15, More about try-except
Aatmaj
Aatmaj

Posted on • Updated on

Learning Python-Basic course: Day 15, More about try-except

Today we will do some practice related to the try error handling we learnt yesterday.


Sample program-

1) Tuple or List? Remember we covered basics of tuples on Day 11? Now we write a program to check if a data type is a List or a Tuple.

a=[1,2,3] #list
b=(1,2,3) #tuple
c=[b,2,4] #list
d=(1,b,c) #tuple
check=[a,b,c,d] 
for i in check:
    try:
        i.append(1)
        print(i," is a List")
    except:
        print(i," is a Tuple")
Enter fullscreen mode Exit fullscreen mode

This example needs strong understanding of Tuples and multidimensional Lists, so in case you are not comfortable with either of them, please refer to Day 11

Output-

[1, 2, 3, 1]  is a List
(1, 2, 3)  is a Tuple
[(1, 2, 3), 2, 4, 1]  is a List
(1, (1, 2, 3), [(1, 2, 3), 2, 4, 1])  is a Tuple
Enter fullscreen mode Exit fullscreen mode

The logic behind this code is that when we try operations like pop, append, push etc. on tuples, they generate errors. We exploit this non-mutable property of Tuples to distinguish between the two. If error generated, it is a Tuple else a List.

Nested try except

We can generate a nested try except in a similar manner, however there is a glitch

try:
    try:
        #statament 1
    except:
        pass
except:
     #statement 2
Enter fullscreen mode Exit fullscreen mode

Here, statement 2 won't ever run. Can you think why?

This is because the first try will not give any error. This is because any no error will be given by the nested try except pass

Here is when we need a nested try is useful.

try:
    #statement 1
    try:
        #statament 2
    except:
        #statement 3
except:
     #statement 4
     # executed if error is in statements 1 or 3
Enter fullscreen mode Exit fullscreen mode

Exercise-

Write a program to check if a number if less than, greater than or equal to 15 without using if -else. (hint use chr() along with try )
Do-Not-See-This-Answer

Comment your answers below. Let's see who can solve this one. 🗡️🛡️ Beware, it is harder than it seems....😉

Discussion (0)