What does “SyntaxError: Missing parentheses in call to 'print'” mean in Python?

前端 未结 8 1311
天命终不由人
天命终不由人 2020-11-21 09:02

When I try to use a print statement in Python, it gives me this error:

>>> print \"Hello, World!\"
  File \"\", line 1
            


        
8条回答
  •  -上瘾入骨i
    2020-11-21 09:27

    Basically, since Python 3.x you need to use print with parenthesis.

    Python 2.x: print "Lord of the Rings"

    Python 3.x: print("Lord of the Rings")


    Explaination

    print was a statement in 2.x, but it's a function in 3.x. Now, there are a number of good reasons for this.

    1. With function format of Python 3.x, more flexibility comes when printing multiple items with comman separated.
    2. You can't use argument splatting with a statement. In 3.x if you have a list of items that you want to print with a separator, you can do this:
    >>> items = ['foo', 'bar', 'baz']
    >>> print(*items, sep='+') 
    foo+bar+baz
    
    1. You can't override a statement. If you want to change the behavior of print, you can do that when it's a function but not when it's a statement.

提交回复
热议问题