DEV Community

Cover image for Day 16: Exceptions - String to Integer | HackerRank | Python
Retiago Drago
Retiago Drago

Posted on

Day 16: Exceptions - String to Integer | HackerRank | Python

The Problem

In this problem, we are given a string, S, and asked to print its integer value. If S cannot be converted to an integer, we are to print 'Bad String'. This task tests our understanding of String-to-Integer conversion and exception handling in Python.

The task also imposes a restriction: we must use the String-to-Integer and exception handling constructs built into our submission language. If we attempt to use loops/conditional statements, we will receive a 0 score.

The Input

The input is a single string, S.

Constraints

  • 1S61 \le \lvert S \rvert \le 6 , where S\lvert S \rvert is the length of string S.
  • S is composed of either lowercase letters (az)( a - z ) or decimal digits (09)( 0 - 9 ) .

Here are some sample inputs:

Sample Input 0:

3
Enter fullscreen mode Exit fullscreen mode

Sample Input 1:

za
Enter fullscreen mode Exit fullscreen mode

The Output

The output should be the parsed integer value of S, or 'Bad String' if S cannot be converted to an integer.

Here are the corresponding outputs for the sample inputs:

Sample Output 0:

3
Enter fullscreen mode Exit fullscreen mode

Sample Output 1:

Bad String
Enter fullscreen mode Exit fullscreen mode

Explanation

Sample Case 0 contains an integer, so it should not raise an exception when we attempt to convert it to an integer. Thus, we print the 3.

Sample Case 1 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'.

The Solution

Let's discuss two different solutions for this problem and their unique attributes.

Source Code 1

The first solution uses a try-except-finally block to handle the conversion of string S to an integer.

S = input()
result = ''
try:
    S = int(S)
    result = S
except Exception as e:
    result = 'Bad String'
finally:
    print(result)
Enter fullscreen mode Exit fullscreen mode

In this code, we first read the input S. We then use a try block to attempt the conversion of S to an integer. If the conversion is successful, we assign the integer value to result. If the conversion raises an exception (which means S cannot be converted to an integer), we catch the exception in the except block and assign 'Bad String' to result. Finally, we print result. The use of the finally block ensures that result is printed whether or not an exception is raised.

Source Code 2

The second solution simplifies the first one by printing directly within the try-except block, eliminating the need for a finally block and a result variable.

S = input()
try:
    S = int(S)
    print(S)
except Exception as e:
    print('Bad String')
Enter fullscreen mode Exit fullscreen mode

In this code, we read the input S and then use a try block to attempt the conversion of S to an integer. If the conversion is successful, we print S directly. If the conversion raises an exception, we catch the exception in the except block and print 'Bad String'.

Both solutions effectively solve the problem, but the second one is more concise. The choice between them depends on whether you prefer to keep your print statements separate from your exception handling code (as in Solution 1) or whether you prefer a more streamlined approach that combines these two steps (as in Solution 2).

Conclusion

This problem is a good demonstration of how exception handling can be used in Python to manage potential errors that can occur when converting data types. Although both solutions effectively solve the problem, they represent different styles of handling exceptions. The first solution separates the printing of the result from the exception handling, while the second one combines these steps for a more streamlined code.

Remember that the style you choose will often depend on the specifics of your problem and your personal coding preferences. It's always beneficial to understand multiple approaches to a problem so you can choose the one that fits your needs best.

You can find the original problem at HackerRank.

For more insightful solutions and tech-related content, feel free to connect with me on my Beacons page.

ranggakd - Link in Bio & Creator Tools | Beacons

@ranggakd | center details summary summary Oh hello there I m a an Programmer AI Tech Writer Data Practitioner Statistics Math Addict Open Source Contributor Quantum Computing Enthusiast details center.

favicon beacons.ai

Top comments (0)