python - 在字典switch语句中模拟'else' [英] python - Simulating 'else' in dictionary switch statements
问题描述
我正在开发一个使用 if,Elif,Elif,... Else
结构的项目,后来我为类似交换的语句更改了结构,如此处和这里。
I'm working on a project which used a load of If, Elif, Elif, ...Else
structures, which I later changed for switch-like statements, as shown here and here.
我将如何添加一个通用的嘿,该选项不存在的情况类似于中的Else,如果,Elif,Else
语句 - 执行的内容如果没有如果
或 Elif
s可以运行?
How would I go about adding a general "Hey, that option doesn't exist" case similar to an Else in an If, Elif, Else
statement - something that gets executed if none of the If
s or Elif
s get to run?
推荐答案
您可以捕获 KeyError
错误,该错误会在地图中找不到值时发生,并返回或处理默认值。例如,使用 n = 3
这段代码:
You could catch the KeyError
error that ensues when a value is not found in the map, and return or process there a default value. For example, with n = 3
this piece of code:
if n == 1:
print 'one'
elif n == 2:
print 'two'
else:
print 'too big!'
成为:
choices = {1:'one', 2:'two'}
try:
print choices[n]
except KeyError:
print 'too big!'
无论哪种方式,'太大了!'
在控制台上打印出来。
Either way, 'too big!'
gets printed on the console.
这篇关于python - 在字典switch语句中模拟'else'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!