Python中如何在函数外部调用函数内部生成的数据
问题核心
函数内部定义的name/age/menu1属于局部作用域变量,仅在函数执行过程中生效,函数运行结束后局部变量会被回收,外部全局环境无法直接访问。你的现有代码存在两个问题:
return {menu1}仅返回了包裹menu1的单元素集合,没有把需要复用的name/age一并返回- 调用
greeting()时没有用变量接收返回值,执行完的结果没有被保存,自然无法在后续代码里调用
修复方案
- 调整
greeting()的返回逻辑,把所有需要外部复用的变量统一返回 - 调用函数时用变量承接返回结果,后续即可在外部直接使用这些值
- 修复
no_responce()递归调用greeting()时的返回值透传问题,避免用户输入n重跑流程后拿不到正确结果
修复后的可运行代码:
def yes_responce(): print("Good! I'm glad i got that right!!!") def no_responce(): print("Oh no! I'm sorry about that! Let me try that again") # 递归调用时透传返回值 return greeting() def greeting(): name = input("Hello, What is your name?") age = input("How old are you?") print("okay,") print("I understood that you name is", name, "and that you are", age, "years old.") menu1 = input("Am I correct? enter y for yes, or n for no.") if menu1 == "y": yes_responce() if menu1 == "n": return no_responce() # 多返回值默认返回元组,不需要额外套集合 return name, age, menu1 # 调用时按顺序接收返回的三个值 user_name, user_age, menu1 = greeting() # 外部可以正常打印使用 print(menu1) print(user_name) print(user_age)
补充说明:如果要跨多层函数复用数据,也可以通过声明全局变量实现,但初学阶段优先用返回值传值的写法,逻辑链路更清晰,不容易出现变量值意外篡改的问题。
内容的提问来源于stack exchange,提问作者Aaron Abair
相关产品推荐
相关产品推荐

