【问题标题】:Python - returns syntax error on request that should workPython - 根据应该工作的请求返回语法错误
【发布时间】:2017-08-02 22:24:39
【问题描述】:

我正在编写一个小程序来创建一个有效的计算器。到目前为止的程序很好,但是我在尝试让我的变量在函数中设置时遇到了这个问题

def request(
  val1 = int(input('Enter the first value: '))
  operation1 = (input('''Enter the operation: '''))
  val2 = int(input('Enter the second value: '))
)

由于某种原因,只有第三行 (operation1) 有错误。不确定python是愚蠢还是我做错了什么

【问题讨论】:

  • (input('''Enter the operation: ''')) 中,外括号没有多大意义。
  • def request(...<code>...) 完全错误。不要将实际代码放在函数声明中。只有参数和默认值。
  • 你需要回到Python tutorial这里,因为你的语法非常非常广泛。 def functionname(..) 语法需要一组以逗号分隔的参数名称,可选择使用默认值和注释。您的代码缺少逗号,我非常怀疑您是否希望 input() 调用为参数提供默认值。
  • 为了将来参考,还请注意“有错误”和“遇到问题”并不是对问题的特别好的描述。

标签: python


【解决方案1】:

我相信python中的函数语法是:

def fxnName(args_if_any):
    val1 = int(input('Enter the first value: '))
    ...

您将所有行包装在函数的参数空间中..

【讨论】:

    【解决方案2】:

    与其他不需要空格的编程语言不同,Python 具有非常严格的函数语法。此外,您使用的语法不正确,因为您使用“()”来定义函数的外部限制。您的函数的正确版本是:

    注意':',然后是缩进。如果删除缩进,它将不会运行。如果你不使用 ':' 它将不起作用。

    def request():
        val1 = int(input('Enter the first value: '))
        operation1 = (input('''Enter the operation: '''))
        val2 = int(input('Enter the second value: '))
    request()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多