How to make a function in python that gets the square for only digits values and does not give an error message when invoked by a string

Viewed 50

I want to make a function in python that gets the square of digit values only and when invoked with a string it does not give an error and instead returns a message. This is what I have reached till now.

What I have tried:

def square(x):
    answer = x
    if answer == answer.int()  :
        print("the square of" ,x, "is", x*x)

    if answer == answer.str() :
        print("please enter a valid number to find its square")

but it gives me the error when invoked with a string such as "joe" as seen here:

Input In [114], in <cell line: 1>()
--->  1 square("joe")

Input In [113], in square(x)
  1 def square(x):
  3     answer = x
--->  4     if answer == answer.int()  :
  5         print("the square of" ,x, "is", x*x)
  7     if answer == answer.str() :

AttributeError: 'str' object has no attribute 'int'
4 Answers
  • int() is a built-in function, not a method. You should be calling int(x) rather than x.int()
  • Use a try-except block. See below:
def square(x):
    try:
        x = int(x)
    except ValueError:
        print("Please enter a valid number to find its square")
        return
    print(f"The square of {x} is {x * x}")

You don’t need to do the logic on this yourself. Let Python handle the error checking (it will throw an error if the user enters a string into what should be an integer).

Instead, you would use try except to decide what to do next on encountering an error.

See the documentation here: https://docs.python.org/3/tutorial/errors.html

You can use type() to find the type of variable.

def square(x):
    if type(x) is int:
        print("The square of {} is {}".format(x, x*x))
    else:
        print("Please enter a valid number to print its square")

by using .int(), you are taking a value (in this case the variable "answer") and trying to turn it into an integer. The reason your code is bringing up errors is because you are using the int() function in the wrong way. Instead of using

    if answer == answer.int()  :

use

    try:
       answer = int(answer) #this will try to turn answer into an integer
    except:
       print("please enter a valid number to find its square") #if answer cannot be turned into an integer, than an error will be raised resulting in the execution of this code segment

it might be worth it to research the "try" and "except" functions more...

Related