gpt4 book ai didi

python - switch return 语句中的多条指令

转载 作者:行者123 更新时间:2023-12-01 01:44:21 24 4
gpt4 key购买 nike

我是 Python 新手。这是我的问题:

import sys

def main():
print "option 1) check updates 2) rewrite index 3) ..."
option = raw_input()
print "\nthe option: is: " + option
switch_option(option)

def switch_option (option):
return {
1:
# print "option is 1",
1,
2: 2

}.get(option, 0)

if __name__ == '__main__':
main()

这个程序工作正常,但如果我取消注释 <print "option is 1" ,我收到错误。
我收到此错误:

SyntaxError: invalid syntax.

我错过了什么?我尝试添加 <,><;> .

问题:

  • 如何在 return 语句中包含调试语句(例如 print)?
  • 在我的例子中,Python 语法是否正在等待某个模板?
  • return 是否接受多个指令?
  • print 会中断执行流程吗?

最佳答案

简短的回答是,您不能按照您建议的方式在表达式中使用 print 语句。您必须回答诸如“何时对其进行评估”之类的问题,某些语言有答案,但 Python 没有。

话虽如此,特别是如果您是 Python 新手但熟悉其他函数式语言,您可以创建一个以函数作为值的字典。这是重新编写示例的方法:

#!/usr/bin/env python3

def main():
print("option 1) check updates 2) rewrite index 3) ...")
option = input().strip()
print("the option: is: " + option)
switch_option(option)

def switch_option (option):
options = {
'1': option_one,
'2': lambda: 2
}
f = options[option]
result = f()
print("the result is: " + str(result))

def option_one():
print("option is 1")
return 1

if __name__ == '__main__':
main()

关于python - switch return 语句中的多条指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51559975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com