Python - Exception Handling

Errors are unavoidable. As a developer, we always have to encounter multiple errors in the initial phase of development. And at the end of the development, the business logic/application which we developed should not misbehave or terminate due to some unexpected events during execution.

In General, Errors in python can be of two types

  • Syntax Errors/Compile Time Error - Syntax mistakes which result in termination of the program.
#syntax error example
a = 5
if(a)
print("Value present")

#result
File "main.py", line 2
    if(a)
        ^
SyntaxError: invalid syntax

HackerRank Python Solution - Errors and Exception - Incorrect Regex

  • You are given a string S.
  • Your task is to find out whether S is a valid regex or not.
Input Format:
  • The first line contains integer T, the number of test cases.
  • The next T lines contain the string S.

HackerRank Python Solution - Errors and Exception

Errors detected during execution are called exceptions.

Examples:

ZeroDivisionError:

This error is raised when the second argument of a division or modulo operation is zero.
 
>>> a = '1'
>>> b = '0'
>>> print int(a) / int(b)
>>> ZeroDivisionError: integer division or modulo by zero

HackerRank Python Solution - Date and Time - Time Delta

  • When users post an update on social media, such as a URL, image, status update, etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published, i.e, how many hours, minutes, or seconds ago.
  • Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format:
  • Day dd Mon yyyy hh:mm:ss +xxxx
  • Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them.

HackerRank Python Solution - Date and Time - Calendar Module

  • The calendar module allows you to output calendars and provides additional useful functions for them.
  • class calendar.TextCalendar([firstweekday])
  • This class can be used to generate plain text calendars.
Sample Code:

HackerRank Python Solution - Collections Topic - Counter()

A counter is a container that stores elements as dictionary keys and their counts are stored as dictionary values.

Sample Code:

>>> from collections import Counter
>>> 
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
>>> print Counter(myList).items()
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>> 
>>> print Counter(myList).keys()
[1, 2, 3, 4, 5]
>>> 
>>> print Counter(myList).values()
[3, 4, 4, 2, 1]

HackerRank Python Solution - Collections Topic - deque()

  • A deque is a double-ended queue. It can be used to add or remove elements from both ends.
  • Deques support thread-safe, memory-efficient appends, and pops from either side of the deque with approximately the same O(1) performance in either direction.

HackerRank Python Solution - Collections Topic - OrderedDict

An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.

Example Code:


>>> from collections import OrderedDict
>>> 
>>> ordinary_dictionary = {}
>>> ordinary_dictionary['a'] = 1
>>> ordinary_dictionary['b'] = 2
>>> ordinary_dictionary['c'] = 3
>>> ordinary_dictionary['d'] = 4
>>> ordinary_dictionary['e'] = 5
>>> 
>>> print ordinary_dictionary
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> 
>>> ordered_dictionary = OrderedDict()
>>> ordered_dictionary['a'] = 1
>>> ordered_dictionary['b'] = 2
>>> ordered_dictionary['c'] = 3
>>> ordered_dictionary['d'] = 4
>>> ordered_dictionary['e'] = 5
>>> 
>>> print ordered_dictionary
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...