【问题标题】:How can I use "Def " and "Return" code in python 3.0 [duplicate]如何在 python 3.0 中使用“Def”和“Return”代码 [重复]
【发布时间】:2021-09-05 10:48:30
【问题描述】:

>>> def square(x):
    return x*x
print (square(4))
SyntaxError: invalid syntax
>>> 

嗨,你能帮我解决这个编程问题吗? 我使用 python 3.0 编写代码,但似乎错误。我从几个无法解决问题的网站上寻找答案。即使我复制了其他代码来编写,它仍然出现错误..

【问题讨论】:

  • 在 Python 中,缩进行的方式很重要。您复制代码 sn-p 的方式并不能真正反映屏幕截图上的内容。所以我假设你搞砸了你的缩进。
  • 您在>>> 提示符处粘贴了多个语句(def print)。 IDLE 不接受这一点。在提示符下键入的所有内容都必须是单个语句或语句的开头。分两步粘贴函数定义和print() 调用。
  • 有帮助,非常感谢
  • 如果将相同的 3 行输入到标准交互式 Python REPL 中,中间行缩进,则会得到相同的错误消息。所以这根本与 IDLE 无关。在 3.10+ 中,IDLE 的 Shell 保持代码行正确排列,就像在 REPL 中一样。我可能会也可能不会将更改反向移植到 3.9。

标签: python syntax-error python-idle


【解决方案1】:

所以 def 使用与 if else 和 for 循环类似的格式。 这意味着您的代码应该类似于

def square(x):
  return x*x
print(square(4)

虽然你可以删掉这个功能而只拥有

print(x^2)

【讨论】:

  • 类似的格式,你可以简单地说函数定义应该缩进。
【解决方案2】:

这是我的例子,你可以检查一下:

def cal(x, y):
    return x+y
print(f"10 + 10 = {cal(10, 10)}")

以及如何使用参数:

def cal(x,y, operation=None):
    opt = ['+', '-', '*', '/']
    if not operation in opt:
        raise TypeError("No Operation To Use")
    elif operation == opt[0]:
        # +
        return x+y
    elif operation == opt[1]:
        # -
        return x-y
    elif operation == opt[2]:
        # *
        return x*y
    elif operation == opt[3]:
        # /
        return x/y
    else:
        print(f"Operation {operation} is unkown")

使用cal(10, 5, operation='+')cal(10, 5, '+') 调用它

最好使用print("Hi") 而不是print "Hi"print ("Hi"),因为 print 不是语法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多