python - 我还能用什么来代替python中的elif、if、else语句?
问题描述
大家好,我想知道我们还能用什么来代替 elif、if、else 语句?或者我如何将给定的 if , elif , else 语句更改为任何其他方法..
假设我有这样的语音助手;
webb = ["open web browser","web browser", "open browser"]
thkns = ["thank you","thank you so much", "thanks"]
fav_web = ["open my favourite web site","favourite web site","my best web site"]
hwaru = ["how are you", "what's up", "how is going"]
thtime = ["whats the time" , "the time", "time"]
def assistant(command):
if command in webb:
talkMe("Opening your web browser")
webbrowser.open("https://www.google.com.tr")
elif command in thkns:
talkMe("You are welcome")
elif command in fav_web:
talkMe("Opening your site")
webbrowser.open("www.stackoverflow.com")
elif command in hwaru:
msg = ["ı am good, you?", "good", "not bad"]
talkMe(random.choice(msg))
elif command in thtime:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
talkMe(f"The time is {strTime} ")
所以我想知道,我还能尝试什么来代替 elif?你能给我解释一下吗?我知道 elif , if 和 else 语句。在这种情况下,如果我想编写其他命令,我必须编写;
elif command in "":
talkMe("")
do some """
elif command in "":
""""
等等..这样行太多可以让代码更短而不是 elif 语句吗?还是我应该继续这样?
解决方案
看起来你可以使用字典。
d = {'Hello Google': obj1, 'open my favourite web site': obj2}
推荐阅读
- r - 如何让代码理解最后一列
- javascript - 如何启用/禁用 BsMultiSelect
- kotlin - 使用 Ktor 时如何将 OutputStream 中的错误传播到客户端?
- kubernetes - 如何根据过滤器在 kubernetes 中获取前 N 个最新创建的 pod
- webpack - 如何使用 Webpack 5 选择性地在 CSS 中内联 SVG?
- ruby - 仅对某些属性使用 group_by
- html - Grails 会打开一个新窗口,但我无法指定窗口大小。如何使用 G:actionSubmit 打开一个较小的窗口?
- sql - Postgres:在另一个表上插入与值一样多的行
- python - 当我尝试发出 http 请求时,它显示为连接错误,而之前它没有显示为连接错误
- java - 在spring boot中将上传的图片保存到静态/图片