What is the quick meaning of the terms print and return in Python?

Question:

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

Asked By: Genoxidus

||

Answers:

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

You want:

print(positiveNumber())
Answered By: Jan

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.

Answered By: Akshath Mahajan

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!

Answered By: Genoxidus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.