0
def math (x,y):
    if x and y == str:
        print(x+y)
        print(x-y)
    else:
        print("Type Number")
math(3,4)

I'm using Python and what I'm trying to do is that I want to plus and minus x and y. If x and y were both numbers then the function will work. Otherwise, if x or y were not numbers then it will say "Type Number" But, the program says "Type Number" even though I typed Number.

kennysliding
  • 2,783
  • 1
  • 10
  • 31
황희윤
  • 441
  • 6
  • 14

3 Answers3

1

In that case, you can use isinstance:

if isinstance(x,int) and isinstance(y,int):
    print(x+y)
    print(x-y)
else:
    print("Type Number")

More about isinstance here

0

You are trying to comparing the variable types of both x and y, and the statement if x and y == str: is not correct.

You may fix it by replacing the line with

if type(x) is int and type(y) is int:

kennysliding
  • 2,783
  • 1
  • 10
  • 31
0

What you have now is checking whether x is true and y is str (this is not equivalent to checking whether its type is a string). What you want is probably this:

def math(x, y):
    if type(x) == int and type(y) == int:
        print(x + y)
        print(x - y)
    else:
        print('Type Number')

math(3, 4)

Here, you're checking the type of x and y to be an integer.

David Lee
  • 665
  • 7
  • 20
  • Thank you so much for helping me! Can I ask one more question? What if I want to plus and minus prime number like 12.2 or 3.6? Then can I write the code like type (x) == int or float? – 황희윤 Jul 02 '21 at 02:41
  • If you also want to allow `float`s then yes, you can do that, but make sure you put parentheses around **int or float**. – David Lee Jul 02 '21 at 02:42