Day 16: Exceptions - String to Integer | HackerRank | Python
Tags: hackerrank, beginners, codenewbie, python
Published: 2023-05-17 16:38:42

## 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

- {% katex inline %} 1 \le \lvert S \rvert \le 6 {% endkatex %}, where {% katex inline %} \lvert S \rvert {% endkatex %} is the length of string `S`.
- `S` is composed of either lowercase letters {% katex inline %} ( a - z ) {% endkatex %} or decimal digits {% katex inline %} ( 0 - 9 ) {% endkatex %}.

Here are some sample inputs:

Sample Input 0:
```
3
```

Sample Input 1:
```
za
```

## 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
```

Sample Output 1:
```
Bad String
```

### 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.

```python
S = input()
result = ''
try:
    S = int(S)
    result = S
except Exception as e:
    result = 'Bad String'
finally:
    print(result)
```

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.

```python
S = input()
try:
    S = int(S)
    print(S)
except Exception as e:
    print('Bad String')
```

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](https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem?isFullScreen=true).

For more insightful solutions and tech-related content, feel free to connect with me on my [Beacons page](https://beacons.ai/ranggakd).

{% embed https://beacons.ai/ranggakd %}