0

我想做这样的事情,在python中是否可能。

f = 'free'
p = 'paid'
if version is f:
      APP_VER = 'APP_FREE'
elif version is p:
      APP_VER = 'APP_PAID'

s_email = webapp2.get_app().config[APP_VER]['SUPPORT_EMAIL']

Error: UnboundLocalError: local variable 'APP_VER' referenced before assignment

任何想法!

4

1 回答 1

5
if version is f:
      APP_VER = 'APP_FREE'
elif version is p:
      APP_VER = 'APP_PAID'

有一种可能性version既不是f也不是p。包括一个else部分。此外(如@jamylak 注释)用于==比较字符串,而不是is

if version == f:
      APP_VER = 'APP_FREE'
elif version == p:
      APP_VER = 'APP_PAID'
else:
    print 'version <{0}> unknown'.format(version)
    exit()
    # or raise an exception here

另一种方式(如果版本列表更长,则改进很大):

app_name = {'free': 'APP_FREE',
            'paid': 'APP_PAID'} # this can be extended if needed
APP_VER = app_name.get(version)
# APP_VER is None if version unknown
于 2012-07-09T07:21:27.280 回答