运行 python 文件中的函数 Git Bash
Running a function in a python file in Git Bash
我有一个名为 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)'
第一个命令行成功运行,但第二行出现语法错误。有什么帮助吗?
尝试在打印函数中添加括号:
$ python -c 'import lab01; print(lab01.sum_digits(10))'
不带括号的语法适用于 python 2,如果您安装的是 Git Bash 模拟器,则应该是 运行 python 3在您的计算机上。
Python 2 打印语句在 Python 3 中被替换为一个函数(因此有括号)。因此您需要使用 print()
.
编辑:此外,如果这是您用于 lab01.py 文件的代码,您的 return 似乎在功能块之外。
我有一个名为 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)'
第一个命令行成功运行,但第二行出现语法错误。有什么帮助吗?
尝试在打印函数中添加括号:
$ python -c 'import lab01; print(lab01.sum_digits(10))'
不带括号的语法适用于 python 2,如果您安装的是 Git Bash 模拟器,则应该是 运行 python 3在您的计算机上。
Python 2 打印语句在 Python 3 中被替换为一个函数(因此有括号)。因此您需要使用 print()
.
编辑:此外,如果这是您用于 lab01.py 文件的代码,您的 return 似乎在功能块之外。