Task - Exception Handling - String to Integer #15
Replies: 10 comments
-
try:
print(int(input("Enter a string")))
except:
print("Bad string") |
Beta Was this translation helpful? Give feedback.
-
string = input(" Enter a word or number: ").strip()
try:
number = int(string)
print(number)
except ValueError:
print('Bad String') |
Beta Was this translation helpful? Give feedback.
-
inp = input()
try:
inp = int(inp)
except:
print("Bad string")
else:
print(inp) |
Beta Was this translation helpful? Give feedback.
-
import sys
S = input("Enter a number or a word: ").strip()
try:
print("The number is:", int(S))
except ValueError:
print(S,"is Bad String.") |
Beta Was this translation helpful? Give feedback.
-
String to Integers = input().strip()
try:
print(int(s))
except:
print("Bad string") |
Beta Was this translation helpful? Give feedback.
-
String to Int# string to int using exception handling
def main():
try:
print(int(input("Enter a number: ")))
except:
print("Bad Number")
if __name__ == "__main__":
main() |
Beta Was this translation helpful? Give feedback.
-
import sys
s = input().strip()
try:
print(int(s))
except:
print("Bad String") |
Beta Was this translation helpful? Give feedback.
-
string = input(" Enter a word or number: ").strip()
try:
num = int(string)
print(num)
except ValueError:
print('Bad String') |
Beta Was this translation helpful? Give feedback.
-
import sys
String = input("Enter a number or word : ").strip()
try:
print("The number is :", int(String))
except ValueError:
print(S," Bad String.") |
Beta Was this translation helpful? Give feedback.
-
1.- S = input().strip()
try:
int(S)
print(S)
except:
print("Bad String") |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Exceptions - String to Integer
Problem
Objective
Today, we're getting started with Exceptions by learning how to parse an integer from a string and print a custom error message.
Task
Read a string,
S
, and print its integer value; ifS
cannot be converted to an integer, printBad String
.Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a
0
score.Input Format
A single string,
S
.Constraints
S
S
is composed of either lowercase letters(a-z)
or decimal digits(0-9)
Output Format
Print the parsed integer value of
S
, orBad String
ifS
cannot be converted to an integer.Sample Input 0
Sample Output 0
Sample Input 1
Sample Output 1
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 the3
.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 printsBad String
.Given code
Beta Was this translation helpful? Give feedback.
All reactions