【发布时间】:2019-02-12 01:21:55
【问题描述】:
这个例子只是一个基本的程序——我是一个新的程序员——一边学习和试验,一边搞砸..目前在 Python 3.6 IDE 和 PyCharm 上进行测试 - 为双倍行距代码道歉 - 但如果没有的话,看起来一团糟。
寻找从函数返回值的指导。
已经尝试了几十种不同的方法/搜索了论坛,但是这个外行可以理解的最接近的答案是我需要使用返回值,否则会被遗忘。所以添加了 print(age_verification," 示例测试值。 . ") 在不同的位置 - 但在函数之外没有返回任何内容..
已尝试返回布尔值/整数/字符串值并进行调整 - 每个变体都没有。在函数之前添加了一个默认的 age_verification = False 变量 // 或 // 第一次在函数中引用。 . 不影响返回值,除了 IDE 没有声明“未解析的引用”
尝试了逐行 python 可视化工具 - 但又一次 - age_verification 值在退出函数后立即消失。 :-(
================================================ ====================
使用 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 .. ")
================================================ ====================
同样的例子 - 使用 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)
================================================ ===============
感谢任何建议 - 今天大部分时间都浪费了我的头撞墙.. 并提前道歉.. 知道这将是非常基本的东西 - 但似乎使用与其他人相同的格式:-)
谢谢
【问题讨论】:
-
要保留返回值,您必须将其保存为名称(或变量,如果您愿意)。因此,如果您有
def add(x, y): return x +y,那么要使用它,您需要执行z = add(1, 6)之类的操作。然后7将被“保存”到z。 -
感谢您的宝贵时间.. 非常感谢..
-
我添加了 age_verification = True (或 ) age_verification = False - "age_verification" 不是一个名字..?
-
或者是仅在计算后返回的值(例如加/减/除),而不是从 False -> True 重新分配值
-
我不确定我是否理解您刚刚发表的第二条评论,但至于
age_verification:如果在函数内部定义了名称,则函数结束后它就会消失。请参阅 C.Nivs 的回答,这就是“范围”
标签: python python-3.x return boolean