返回函数中的变量 Python 无法正常工作 [英] Returning Variables in Functions Python Not Working Right

查看:42
本文介绍了返回函数中的变量 Python 无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在一个变量中返回一个函数中的一个变量并在它之外使用它:

I have been trying to return a variable in a function in a variable and use it outside of it:

test = 0

def testing():
    test = 1
    return test

testing()
print(test)

但是当我运行它时,结果是 0.我该如何解决这个问题?

But when I run it, the result is 0. How could I fix this problem?

推荐答案

你搞砸了范围和/或分配.试试这个:

You are messing up a bit the scopes and/or assignment. Try this:

def testing():
    test = 1
    return test

test = testing()
print(test)

说明:testing 内的test 与模块内的test 不同.您必须在模块级别分配它才能获得预期的结果.

Explanation: The test inside testing is different to the test inside the module. You have to assign it on module-level to get the expected result.

这篇关于返回函数中的变量 Python 无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆