【问题标题】:Python: Submitting Multiple Commands At OncePython:一次提交多个命令
【发布时间】:2018-07-01 00:05:17
【问题描述】:

当我在 IDLE 中一次提交多个命令时(使用 v. 3.7),我收到“无效语法”错误。

例如,我必须先复制、粘贴,然后输入:

def converter(number, base):
    figures = [int(i) for i in str(number)]
    figures = figures[::-1]
    result = 0
    for i in range(len(figures)):
        result += figures[i]*base**i
    return result

然后我必须复制、粘贴并输入:

print(converter(30, 12))

很繁琐,一起输入很方便。有没有办法做到这一点?

编辑: 为了清楚起见,这是一个快速视频示例: https://www.dropbox.com/s/gh3zxc8qy3jjl7p/python.mp4?dl=0

【问题讨论】:

  • 一旦定义了函数,除非定义已更改,否则您不必再次复制/粘贴它。没有机制可以预测您要传递给 converter 的参数,但如果您可以调用 print(converter()),则可以为参数提供默认值。
  • 如果您想编辑旧功能而无需复制/粘贴,可以点击up 箭头键。见How do I access the command history from IDLE?
  • 我不知道“一次输入多个命令”是什么意思。您需要提供minimal reproducible example
  • @juanpa.arrivillaga 我的意思是把 def 和 print 一起复制,粘贴在一起,然后一起输入,而不是单独做。
  • @ChiefTwoPencils 不过,为什么我必须将 def 与 print 分开输入。如果 Python 是按顺序读取的,应该可以处理同时输入的。

标签: python


【解决方案1】:

我自己想出来的。您只需将所有命令嵌入到 if 语句中。

if 1:
    def converter(number, base):
        figures = [int(i) for i in str(number)]
        figures = figures[::-1]
        result = 0
        for i in range(len(figures)):
            result += figures[i]*base**i
        return result

    print(converter(30, 12))

【讨论】:

  • 你不需要这样做。您需要在独立代码块之间添加新行。这是交互式解释器的一个怪癖。从根本上说,shell 不应该是一个开发环境。它用于快速而肮脏的调试和实验。或许你应该考虑ipython shell,它比默认的功能更全,并且更智能地处理复制和粘贴
猜你喜欢
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多