-3

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'
quamrana
  • 37,849
  • 12
  • 53
  • 71
Joe
  • 3
  • 3
  • Example of how to use [int](https://www.learnbyexample.org/python-int-function/). – jarmod Sep 08 '22 at 15:16
  • 1
    What do you think `answer.int()` does? Try it out in a python terminal. – blackbrandt Sep 08 '22 at 15:16
  • 1
    Does this answer your question? [Checking whether a variable is an integer or not](https://stackoverflow.com/questions/3501382/checking-whether-a-variable-is-an-integer-or-not) – s_pike Sep 08 '22 at 15:18
  • 2
    `int(answer)` instead of `answer.int()`. Please do not presume to *guess* how to code the program can meet your requirements. On the contrary, if you are not sure, search for them. – Mechanic Pig Sep 08 '22 at 15:18
  • Try to use the `isinstance` function which returns a boolean if it match to correct type, here's a link [use isistance to check the type of an object](https://www.w3schools.com/python/ref_func_isinstance.asp) –  Sep 08 '22 at 15:45

4 Answers4

0
  • 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}")
djurgen
  • 26
  • 3
  • Don't simply return. It's better to raise an exception and *force* the caller to deal with it than to return `None` and *hope* the caller ensures an integer was returned. – chepner Sep 08 '22 at 15:41
  • @chepner The function is already returning `None` so returning early isn't a problem. It also wouldn't necessarily make sense to raise an exception because I'm handling the exception already. If the user needs to handle the exception then what is the point in my function handling it at all? – djurgen Sep 09 '22 at 16:33
  • I didn't read the function carefully, and assumed that it was returning the square of the number when there was no exception. Since it returns `None` in every case, there is indeed no problem. – chepner Sep 09 '22 at 19:18
0

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

Joel
  • 135
  • 9
0

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")
Anjaan
  • 595
  • 5
  • 19
  • `if isinstance(x, int)`. Comparing types directly breaks in the case of subclassing. – chepner Sep 08 '22 at 15:40
  • OP asked how can he know if x is integer or not so I gave a simple answer for single use case. – Anjaan Sep 08 '22 at 15:45
  • `class X(int): pass; square(X(5))`. `X(5)` is an `int`, yet your code rejects it. – chepner Sep 08 '22 at 16:01
  • Thank you very much but I could not figure out what's the use of .format in print("The square of {} is {}".format(x, x*x)). – Joe Sep 10 '22 at 14:18
  • @Joe When there are variables in your string you can use {} inside the string and format the string to replace the {} with values you need. But you should maintain the order of occurrence of {} while providing format values. Hope you can understand from this explanation. – Anjaan Sep 12 '22 at 01:26
-1

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...

CR130
  • 98
  • 7