简体   繁体   English

Python - 函数返回值

[英]Python - Function Return Value

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.这个例子只是一个基本的程序 - 我是一个新的编码员 - 学习和实验,同时搞砸了......目前正在 Python 3.6 IDE 和 PyCharm 上进行测试 - 为双倍间距代码道歉 - 但没有看起来一团糟。

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 ..尝试了几十种不同的方法/搜索了论坛,但是这个外行能理解的最接近的答案说我需要使用返回值否则它会被遗忘..所以在不同的位置添加了print(age_verification, "example test value ..") - 但在函数之外没有返回任何东西..

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"已尝试返回布尔值/整数/字符串值并进行调整 - 每个变体都没有。在函数之前添加了默认的age_verification = False变量 // 或 // 在函数中第一次引用 .. 不影响返回值,除了 IDE没有说明“未解决的参考”

Tried a line-by-line python visualizer - but again - age_verification value disappears instantly after exiting the function .尝试了逐行 python 可视化工具 - 但再次 - 退出函数后,age_verification 值立即消失。 :-( :-(

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

Using 1 Single Function使用 1 个单一功能

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相同示例 - 使用 2 个函数

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谢谢你

print doesn't return values, it will just display the value to stdout or the console. print不返回值,它只会将值显示到stdout或控制台。 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. print语句将抛出NameError因为var2未在函数外部定义,也未返回。 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这样您就可以将返回值保存为变量age_verification

EDIT:编辑:

To further expand on the scope concept, using the same definition for my_func :为了进一步扩展范围概念,对my_func使用相同的定义:

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

We assign the returned var3 to a variable like so:我们将返回的var3分配给一个变量,如下所示:

myvar = my_func(5)

As noted, the name var3 isn't actually returned, just the value.如前所述,名称var3并未实际返回,仅返回值。 If I were to run如果我要跑

myvar = my_func(5)
print(var3)

I would get a NameError .我会得到一个NameError The way to get around that would be to do:解决这个问题的方法是:

var3 = my_func(5)

because now var3 is defined in global scope.因为现在var3是在全局范围内定义的。 Otherwise, I would have to edit my function to make var3 global:否则,我将不得不编辑我的函数以使var3全局化:

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希望这比我原来的答案更清楚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM