0

I'm doing some Kaggle exercises and the question is asking me to "In the cell below, define a function called sign which takes a numerical argument and returns -1 if it's negative, 1 if it's positive, and 0 if it's 0". This was my function:

def sign(x):
    if x < 0:
        print('-1')
    elif x > 0:
        print('1')
    else:
        print('0')

I tested on VS Code but Kaggle saying it's "incorrect". The proper solution it's the following:

def sign(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0

I would like to know what's the real difference between my function and Kaggle's? Cheers

  • Actually this question is a duplicate of [What is the purpose of the return statement? How is it different from printing?](https://stackoverflow.com/q/7129285/11659881). If anyone votes to close as duplicate please use this link instead. I have no idea why it was way lower on the page than the other link when I searched for this question on StackOverflow. – Kraigolas Aug 25 '22 at 00:13

1 Answers1

0

The difference between print and return is that when you use print, you don`t have to call your function with print, example:

def sign(x):
    if x > 0:
        print('123')
    elif x < 0:
        print('134')
    else:
        print('Hey')

sign(1) # That is how you call your func with no print

Otherwise, if you use returns in your code, than you have to use print when you call your fucn, example:

def sign(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0

print(sign(1)) # That is how you call your func with print

Also if you need to get the result value of func, then you can assign a value to a variable, example:

def func(x=0):
    x = x ** 2
    return x

a = func(5)
print(a) # 25
rockzxm
  • 342
  • 1
  • 9