首页 > 解决方案 > 函数返回变量而不是变量的赋值

问题描述

我在 Python 中有一个相当简单的代码(见下文),但无法弄清楚为什么“选择”变量不返回分配的变量全局值而不是函数中的变量。例如,如果我运行函数“drink_coffee”,当我选择“a”时,返回的值应该是“cappuccino”。相反,它返回“a”。但是如果我从函数中打印“a”,它会返回“cappuccino”。有什么我想念的想法吗?

a = 'cappuccino'
b = 'espresso'
c = 'latte'


def drink_coffee():
    '''Returns the coffee the user would like to drink'''
    global a, b, c
    selection = input("What would you like to drink? A: cappuccino, B: espresso, C:latte? ").lower()
    print(selection)
    print(a)
    return selection

喝咖啡()

标签: python

解决方案


内容为字母的字符串a与包含某些内容的名为 a 的变量之间存在差异。

在您的代码中,您将用户输入分配给变量,该变量selection将包含用户输入的任何字符串。

我认为您在这里想要的是将您的字母到饮料的映射存储在字典中。它可能看起来像这样:

drink_mappings = { "a" : 'cappuccino',
                   "b" : 'espresso',
                   "c" : 'latte' }

然后,当用户提供 a、b 或 c 字符串时,您可以使用drink_mappings字典解析并返回映射的饮料名称:

例如

def drink_coffee():
    '''Returns the coffee the user would like to drink'''
    
    selection = input("What would you like to drink? A: cappuccino, B: espresso, C:latte? ").lower()
    print(drink_mappings.get(selection, "Nothing") )
    print(a)
    return drink_mappings.get(selection, "Nothing")

这应该给你你想要的行为。不过一般来说,您通常不能使用通过用户输入输入的字符串值直接引用变量名。虽然可以使用一些自省代码 - 但这可能不是这类事情的最佳用途。出于兴趣,这可能是如何工作的:

def drink_coffee():
'''Returns the coffee the user would like to drink'''
global a, b, c
selection = input("What would you like to drink? A: cappuccino, B: espresso, C:latte? ").lower()
print(selection)
print(a)
return globals()[selection]

它使用包含globals()所有当前活动全局变量的字典,并允许您通过与其名称匹配的字符串来引用它们。locals()如果您不喜欢使用全局变量,那么有一个类似的内置字典会做类似的事情。

但这是一件非常奇怪的事情,如果他们看到这样的用例,人们会难以置信地眯起眼睛。例如,任何运行此代码的用户都可以通过键入其名称来访问当前处于活动状态的任何变量或函数。这会引发一些严重的安全问题,并且会被认为是一个非常大的禁忌。


推荐阅读