语法错误:调用“打印”时缺少括号 (Python)

语法错误:调用“print”时缺少括号 (Python)

SyntaxError: Missing parentheses in call to ‘print’ (Python)

Python“SyntaxError:调用‘print’时缺少括号。你是说 print(…)?” 当我们忘记print()作为函数调用时会发生。

要解决该错误,请使用括号调用 print 函数,例如
print('hello world')

调用打印时语法错误缺少括号

下面是错误如何发生的示例。

主程序
name = 'Bobby' # ⛔️ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)? print 'hello ' + name

调用打印时缺少括号

上面的代码使用printas 语句,这是 Python 2 中使用的旧语法。

主程序
# ⛔️ this code only works in Python 2 print 'bobbyhadz.com' # ✅ this code works in Python 3 print('bobbyhadz.com')

如果您需要检查 Python 版本,请使用该python --version命令。

python --version

获取 python 版本

将 print() 作为函数调用

从 Python 3 开始,print()现在是一个函数,应该用括号调用。

主程序
name = 'Bobby' print('hello ' + name) # 👉️ "hello Bobby"

我们使用括号调用了print()函数,将我们要打印的字符串传递给它。

使用 print 作为表达式在 Python 3 中不再有效。

主程序
# ⛔️ this no longer works in Python 3 print 'bobbyhadz.com' # ✅ call print() as a function instead print('bobbyhadz.com')

sep如果需要,您还可以指定(分隔符)关键字参数。

主程序
print('a', 'b', 'c', sep="_") # 👉️ "a_b_c" print('a', 'b', 'c', sep="_", end="!!!") # 👉️ "a_b_c!!!"

我们为end关键字参数传递的字符串
被插入到字符串的末尾。

使用print()带有格式化字符串文字的函数

print()函数通常与
格式化字符串文字一起使用。

主程序
name = 'Bobby' salary = 100 # Employee name: # Bobby # salary: 200 print(f'Employee name: \n {name} \n salary: {salary * 2}')

格式化字符串文字 (f-strings) 让我们通过在字符串前加上f.

主程序
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces – {expression}.

# If your code should run in both Python 2 and Python 3

You can add an import statement to import the print function from the
__future__ module if your code should be able to run in both Python 2 and
Python 3.

main.py
# ✅ can now use the print() function in Python 3 from __future__ import print_function print('bobbyhadz.com')

We imported the print_function from __future__, so now we are able to use
print as a function in Python 2.

You can use this approach to make your code Python 3 compatible.

# Use the 2to3 package to make your code Python 3 compatible

You can install the 2to3 package by running
the following command.

shell
pip install 2to3 pip3 install 2to3 python -m pip install 2to3 python3 -m pip install 2to3 py -m pip install 2to3

The package is used to make your code Python 3 compatible.

You can run the package for a single file with the following command.

shell
2to3 -w main.py

使用 2to3 使代码兼容 python3

Make sure to replace main.py with the name of your module.

You can also use the 2to3 module on all files in the directory.

main.py
2to3 -w .

The print statements in your code should get converted to calls to the
print() function as shown in the gif.

Want to learn more about using the print() function in Python? Check out these resources: How to Print on the Same Line in Python,How to print Integer values in Python.

# Additional Resources

You can learn more about the related topics by checking out the following
tutorials: