Computer Science
Show how to modify the following code so that an error is printed if the number conversion is not successful:
val = input("Enter a number")
pval = int(val)
Answer
val = input("Enter a number: ")
try:
pval = int(val)
except ValueError:
print("Error: Conversion to integer failed.")
Output
Enter a number: 23
Enter a number: python
Error: Conversion to integer failed.
Explanation
In this modified code the input function prompts the user to enter a number. The try block attempts to convert the input value to an integer using int(val)
. If the conversion is successful, pval
will hold the integer value. If the conversion raises a ValueError (e.g., if the input is not a valid integer), the program jumps to the except block and prints an error message indicating that the conversion to an integer failed.
Related Questions
What does the finally clause produce in a try…except block?
Write syntax of raise statement.
Differentiate between IOError and IndexError.
Consider the code given below and fill in the blanks with appropriate error types:
loop = 1 while loop == 1: try: a = int(input('Enter the first number: ') b = int(input('Enter the second number: ') quotient = a/b except ...............: print("Error: Please enter only numbers") except ...............: print("\n Error: Second number should not be zero") except ...............: print("\n Unsupported operation: Check the date type") else: print("Great") finally: print("Program execution completed") loop = int(input('Press 1 to try again !') continue