Skip to main content
 首页 » 编程设计

Python之函数返回值

2024年12月31日9dudu

<分区>

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

寻找有关从函数返回值的指南。

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

已尝试返回 boolean 值/整数/字符串值并进行调整 - 每个变体都没有。在函数之前添加默认 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) 

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

感谢任何建议 - 今天大部分时间都浪费了我的头撞墙..提前道歉..知道这将是非常基本的东西 - 但似乎使用与其他人相同的格式:-)

谢谢