You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派终端运行Python脚本时print命令输出带括号问题求助

Why Your Python Script Outputs a Tuple & Works Without Print Parentheses on Raspberry Pi

Hey there! Let's unpack what's going on here—this is a super common mix-up with Python versions, especially on Raspberry Pi which usually has both Python 2 and Python 3 pre-installed.

The Root Cause: You're Running Python 2 Instead of Python 3

Here's why you're seeing those unexpected behaviors:

  1. Tuple-style output
    In Python 3, print() is a built-in function, so when you write print(num, "is a prime number"), it prints the values separated by spaces (like 5 is a prime number). But in Python 2, print is a statement, not a function. When you use parentheses with the print statement in Python 2, it treats the contents as a single tuple object—hence the output (5, 'is a prime number').

  2. Print works without parentheses
    Again, this is Python 2 behavior. In Python 2, the print statement doesn't require parentheses (e.g., print "Hello world" is perfectly valid). In Python 3, omitting parentheses would throw a syntax error because print is strictly a function there.

How to Fix It

Follow these steps to get the expected behavior:

  • Check your Python versions
    Run these commands in your terminal to confirm which versions are installed:

    python --version
    python3 --version
    

    You'll likely see that python points to Python 2.x, while python3 points to Python 3.x.

  • Run your script with Python 3
    Instead of using python your_script.py, use:

    python3 your_script.py
    

    This will execute your code with Python 3, where print() acts as a function and gives you the clean output 5 is a prime number.

  • Make it permanent with a shebang line
    Add this line at the very top of your Python script:

    #!/usr/bin/env python3
    

    Then give the script executable permissions:

    chmod +x your_script.py
    

    Now you can run it directly with ./your_script.py, and it will automatically use Python 3.

内容的提问来源于stack exchange,提问作者Josh B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:04:13