HackerRank Day 16 Solution: Exceptions – String to Integer

Today we will see the HackerRank Day 16 Solution in Python. The problem is named Exceptions – String to Integer which is part of 30 Days of code on HackerRank. Let’s get started!

Day 16: Exceptions – String to Integer Problem statement

Our task is to read a string and print its integer value. If the String cannot be converted to an integer, then we have to print BadString. We must use the String-to-Integer and exception-handling and should not use loops/conditional statements.

Sample Input

cat

Sample Output

Bad String

Explanation

Input does not contain any integers, so an attempt to convert it to an integer will raise an exception. Thus, our exception handler prints Bad String.

You can solve the problem here.

HackerRank Day 16 Solution in Python

#!/bin/python3

import math
import os
import random
import re
import sys

#To Get input String
S = input().strip()

#Try to print int value of string
try:
    print(int(S))

#If error found, print Bad String
except ValueError:
    print("Bad String")

Code Explanation:

  • First, get the input String
  • Then, in the try block convert the String to an integer and print the value
  • If an exception is found(i.e., no integer value found in the String) then print Bad String

Also Read:

Share:

Author: Ayush Purawr