This website collects cookies to deliver better user experience
Learning Python-Basic course: Day 15, More about try-except
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]#listb=(1,2,3)#tuplec=[b,2,4]#listd=(1,b,c)#tuplecheck=[a,b,c,d]for i in check:try: i.append(1)print(i," is a List")except:print(i," is a Tuple")
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
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 tryexcept
We can generate a nested tryexcept in a similar manner, however there is a glitch
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 tryexcept pass
Here is when we need a nested try is useful.
try:#statement 1try:#statament 2except:#statement 3except:#statement 4# executed if error is in statements 1 or 3
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....😉