我想做这样的事情,是否可以在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
任何想法!
答案 0 :(得分: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