gpt4 book ai didi

python - 替换Python中的变量

转载 作者:行者123 更新时间:2023-11-30 23:43:50 26 4
gpt4 key购买 nike

这是我的脚本:

fruit  = "apple"
phrase = "I like eating " + fruit + "s."

def say_fruit(fruit):
print phrase

say_fruit('orange')

我试图让 say_fruit 使用 phrase 变量中给定的字符串,该变量实际上使用之前已经分配给它的变量(apple)。我怎样才能实现这个目标?

最佳答案

在您的代码中,phrase 在模块加载时绑定(bind)到字符串,并且永远不会更改。你需要保持活力,就像这样:

def phrase(fruit):
return "I like eating " + fruit + "s."

def say_fruit(fruit):
print phrase(fruit)

全局变量只是一个坏主意,将来会困扰你。抵制使用它们的诱惑。

关于python - 替换Python中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10568079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com