KnowledgeBoat Logo

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)

Python Exception Handling

3 Likes

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.

Answered By

3 Likes


Related Questions