Python - Function Return Value

10,825

print doesn't return values, it will just display the value to stdout or the console. If you want to return a value with conditions, understanding scope is helpful. Your comment regarding returning variables otherwise they will be "forgotten" is correct. Variables defined and not returned by the function will go away when the function executes:

def my_func(var1):
    var2 = var1
    var3 = 5
    return var3

print(my_func(1), var2)

The print statement will throw a NameError because var2 isn't defined outside of the function, nor is it returned. For your example, you'd want something like this:

def age_verify(age):
    if age < 18:
        print("Failed Verification")
        return False
    else:
        print("Verification Complete")
        return True

# Call and assign to var
age = int(input("Enter Your Age : ")
age_verification = age_verify(age)

This way you are saving the returned value as the variable age_verification

EDIT:

To further expand on the scope concept, using the same definition for my_func:

def my_func(var1):
    var2 = var1
    var3 = 5
    return var3

We assign the returned var3 to a variable like so:

myvar = my_func(5)

As noted, the name var3 isn't actually returned, just the value. If I were to run

myvar = my_func(5)
print(var3)

I would get a NameError. The way to get around that would be to do:

var3 = my_func(5)

because now var3 is defined in global scope. Otherwise, I would have to edit my function to make var3 global:

def my_func(var1):
    global var3
    var2 = var1
    var3 = 5
    # The return statement is then a bit redundant

my_func(5)

print(var3)
# prints 5 in global scope

Hopefully this is a bit clearer than my original answer

Share:
10,825
Guybrush_Threepwood
Author by

Guybrush_Threepwood

Updated on June 04, 2022

Comments

  • Guybrush_Threepwood
    Guybrush_Threepwood almost 2 years

    This example is just a basic program - I'm a new Coder - learning and experimenting whilst messing about .. Currently testing on Python 3.6 IDE and PyCharm - apologies for double spacing code - but looks a mess without.

    Looking for guidance for returning a value from a function.

    Have tried dozens of different methods / searched the forum, but closest answer this layman could understand stated I needed to use the return value otherwise it will be forgotten .. So added print(age_verification, " example test value .. ") at various locations - but nothing gets returned outside the function ..

    Have tried returning Boolean / integer / string values and adapting - nothing with each variant .. Added a default age_verification = False variable before the function // or // referenced within function for 1st time .. Doesn't effect the return value except IDE doesn't state "unresolved reference"

    Tried a line-by-line python visualizer - but again - age_verification value disappears instantly after exiting the function . :-(

    ==================================================================

    Using 1 Single Function

    def age_veri(age, age_verification) :
    
      if age < 18 :
    
        age_verification = False
    
        print(age_verification, " is false .. Printed to test variable ..")
    
        return age_verification
    
      elif age >= 18:
    
        age_verification = True
    
        print(age_verification, " is True.. Printed to test variable ..")
    
        return age_verification
    
      return age_verification # ( -- have tested with/without this single-indent line & with/without previous double-indent return age_verification line.)
    
    age=int(input("Enter Your Age : ")
    
    age_verification = False # ( -- have tried with / without this default value)
    
    age_veri(age, False)
    
    if age_verification is False:
    
      print("You failed Verification - Age is Below 18 .. ")
    
    elif age_verification is True:
    
      print("Enter Website - Over 18yrs")
    
    else:
    
      print(" Account not Verified .. ")
    

    ==================================================================

    Same Example - Using 2 Functions

    def age_variable(age):
    
       if age < 18:
    
          age_verification = False
    
          print (age_verification, " printing here to use value and help test function..")
    
          return age_verification
    
       elif age >= 18:
    
          age_verification = True
    
          print (age verification, " printing here to use value and help test function..")
    
          return age_verification
    
       return age_verification (tried with and without this line - single indent - same level as if / elif) 
    
    def are_verified(age_verification):
    
       if age_verification is False:
    
          print("Age Verification Failed .. ")
    
       elif age_verification is True:
    
          print("Visit Website .. ")
    
       else:
    
          print("Verification Incomplete .. ")
    
    age = int(input("Enter Your Age : ")
    
    age_variable(age)
    
    are_verified(age_verification)
    

    ==============================================================

    Any advice is appreciated - wasted most of today hitting my head against the wall .. And apologies in advance .. Know it'll be something really basic - but appear to be using same formatting as others :-)

    THANK YOU

    • HFBrowning
      HFBrowning over 5 years
      To retain a returned value you must save it to a name (or variable, if you like). So if you had def add(x, y): return x +y then to use it you'd need to do something like z = add(1, 6). Then 7 will be "saved" to z.
    • Guybrush_Threepwood
      Guybrush_Threepwood over 5 years
      Thank you for your time .. It is appreciated ..
    • Guybrush_Threepwood
      Guybrush_Threepwood over 5 years
      I've added age_verification = True ( or ) age_verification = False - is "age_verification" not a name ..?
    • Guybrush_Threepwood
      Guybrush_Threepwood over 5 years
      Or are values only returned after computation (eg add / subtract / divide ) rather than reallocating a value from False -> True
    • HFBrowning
      HFBrowning over 5 years
      I'm not sure I understand the second comment you just made, but as for age_verification: if a name is defined inside of a function it disappears once the function is over. See C.Nivs' answer, this is what "scope" is
    • HFBrowning
      HFBrowning over 5 years
      Contemplate: def add(x, y): z = x; return z +y and then running it z = add(1, 6). Same answer as before. z is one thing while inside the function; once the function is done it disappears. Outside the function the equal sign means the new z gets assigned the function's return value.
  • HFBrowning
    HFBrowning over 5 years
    This is a good answer but I would edit slightly to make it clear that even if you had written print(var3) after defining my_func, it still wouldn't have worked. Saying " because var2 isn't defined outside of the function, nor is it returned" could be confusing to newbies. The name attached to a return value is not returned (unless you used global)
  • Guybrush_Threepwood
    Guybrush_Threepwood over 5 years
    Many thanks C.Nivs and @HFBrowning .. Honestly, your time and help is appreciated .. I'm a newbie - learning via YouTube and my "Dummies Guide to Python" book . Sometimes these sources don't clearly explain everything .. Wishing you both success and fortune :-)
  • HFBrowning
    HFBrowning over 5 years
    You're welcome :) If you feel that C.Nivs' answered your question, you can accept it with the checkmark under the upvote/downvote on their answer.
  • C.Nivs
    C.Nivs over 5 years
    @HFBrowning I added your suggestion to my answer, thanks