Search code examples
pythonprintingreturn

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


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


Solution

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

    You want:

    print(positiveNumber())