Square of an Integer with Exception Handling

Write a Python program that asks the user for an integer input and returns the square of it. If the input is not an integer, return the string “Error: Input is not an integer”.

Example 1:

Input: "5"

Output: 25

Example 2:

Input: "abc"

Output: "Error: Input is not an integer"

Use try-except block to handle ValueError which occurs when non-integer is converted to integer.

def square():
    try:
        num = int(input())
        return num ** 2
    except ValueError:
        return "Error: Input is not an integer"

print(square())  # Output: 25 if input was 5
print(square())  # Output: "Error: Input is not an integer" if input was abc

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!