Python中无法通过局部变量从自定义函数获取值的求助
问题分析与解决方案
问题根源
- 参数传递错误:调用
sth('chaddar')和basic('chaddar')时,传递的是字符串字面量'chaddar'而非变量,导致basic函数中chaddar是字符串类型,和整数1比较永远不成立。 - 局部变量未返回:
sth函数内部修改了局部变量chaddar的值,但没有通过return返回,外部无法获取修改后的结果。
修正后的代码
def sth(chaddar): chaddar = 1 return chaddar # 返回修改后的局部变量值 def basic(chaddar): horn = input("answer: ") if chaddar == 1 and "yes" in horn: print("ok") else: print("error") # 获取sth返回的chaddar值,再传递给basic chaddar_val = sth(0) # 初始值不影响,函数内会重置为1 basic(chaddar_val)
如果sth不需要接收初始参数,可进一步简化:
def sth(): return 1 # 直接返回目标值 def basic(chaddar): horn = input("answer: ") if chaddar == 1 and "yes" in horn: print("ok") else: print("error") basic(sth())
验证效果
运行修正后的代码,输入yes时会输出ok,其他情况输出error,完全符合需求。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

