为什么变量在 def 函数中不存储内容

why variable doesn't store stuff when inside a def funct

我是编程新手! 当我这样做时:

>>>x = "heyy"
>>>def hello():
       x = "hi"
>>>hello()
>>>print(x)
heyy

为什么 x 仍然是 "heyy"? 无论如何我可以把 x = hi 变成一个全局变量吗?不使用 "return" 并将其放入新变量中? 喜欢:

>>>x = "heyy"
>>>def hello():
    x = "hi"
    return x
>>>y = hello()
>>>print(y)
hi

基本上我只是想将 x 的内容更改为 hi 而不是 heyy 当我 运行 hello()

您可以使用 global 关键字来做到这一点

def hello():
   global x
   x = "hi"

但请务必注意,这是一种不好的做法,应尽可能使用return。这是因为在任何方法中变量的值都有可能被破坏