0

I'm learning some new things, and I cannot figure out the whole return process from reading my texts and looking online. I believe I need it explained to me once for me to wrap my head around it.

The code here works as intended; I would like the user to input a number, then if less than 0, print 0, if greater than or equal to zero print the number.

def positiveNumber():
    num = int(input("Please enter a number: "))
    if num <= 0:
        print("0")
    else:
        print(num)

positiveNumber()

What isn't working is where I just want the function to return the values, then only give me the answer when I call the function.

def positiveNumber():
    num = int(input("Please enter a number: "))
    if num <= 0:
        return 0
    else:
        return num

positiveNumber()
print(num)

My shell keeps telling me "name 'num' is not defined".

Genoxidus
  • 51
  • 1
  • 6
  • 2
    `num` is a local variable that only exists in `positiveNumber()`. You might be looking for `print(positiveNumber())`. – Jan Mar 29 '20 at 20:24
  • might be worth to check out "scope of variables": https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#variable-scope-and-lifetime – Yevgen Ponomarenko Mar 29 '20 at 20:28

3 Answers3

3

num is a local variable that only exists in positiveNumber().

You want:

print(positiveNumber())
Jan
  • 42,290
  • 8
  • 54
  • 79
  • So, would this be saying that I don't really call my function? Instead I'm just printing the result of it? – Genoxidus Mar 29 '20 at 20:40
  • @Genoxidus That is incorrect. You ARE calling the function. When the function terminates, it returns its return value, which is then printed. – Paul M. Mar 29 '20 at 21:04
1

The variable num is defined within your function. It thus only exists in the "scope" of the function. When you're calling the function, you should try

a = positiveNumber()
print(a)

The returned value is something that you should assign to a variable in order to use. Your function is sending back the value of num So you can either

print(positiveNumber())

Or you can store it somewhere, and then use that. This happens because the name num only exists inside the function, it's computed and the VALUE is being returned. So you can either directly print this VALUE or you could store it in some variable and then use it.

Akshath Mahajan
  • 248
  • 2
  • 11
0

Here is the code that worked:

def positiveNumber():
    num = int(input("Please enter a number: "))
    if num <= 0:
        return 0
    else:
        return num

print(positiveNumber())

Thank you so much!

Genoxidus
  • 51
  • 1
  • 6