【问题标题】:Running a function in a python file in Git Bash在 Git Bash 中的 python 文件中运行函数
【发布时间】:2020-08-11 18:07:27
【问题描述】:

我有一个名为 lab01.py 的 python 文件,它包含两个函数

def both_positive(a, b):
     return a > 0 and b > 0

def sum_digits(x):
     """
     Sum all the digits of x.
     """
     ans = 0
     num = str(x)
     for ele in num:
         ans += eval(ele)
return ans

我需要在 Git Bash 中打印 sum_digits(x) 函数的输出。这是我输入的命令行

$ cd ~/desktop/programming/lab01
$ python -c 'import lab01; print lab01.sum_digits(10)'

第一个命令行运行成功,但第二行出现 SyntaxError。有什么帮助吗?

【问题讨论】:

标签: python git-bash


【解决方案1】:

尝试在打印函数中添加括号:

$ python -c 'import lab01; print(lab01.sum_digits(10))'

不带括号的语法适用于 python 2,如果你的计算机上安装了 python 3,你的 Git Bash 模拟器应该运行 python 3。

Python 2 的打印语句在 Python 3 中被替换为函数(因此是括号)。所以您需要使用 print()

编辑:另外,如果这是您用于 lab01.py 文件的代码,那么您的返回似乎在功能块之外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 2014-05-17
    • 1970-01-01
    • 2021-07-07
    • 2015-12-05
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    相关资源
    最近更新 更多