在Git Bash中的python文件中运行函数
我有一个名为lab01.py的python文件,它包含两个函数在Git Bash中的python文件中运行函数,python,git-bash,Python,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 我
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))'
不带括号的语法适用于Python2,如果计算机上安装了Python3,那么Git Bash仿真器应该运行Python3
在Python3中,Python2的print语句被替换为一个函数(因此是括号)。因此,您需要使用print()
编辑:另外,如果这是您用于lab01.py文件的代码,您的返回似乎在功能块之外。oarens用于打印函数调用
()
@Alan Hoover感谢您的帮助!你是说$python-c'导入lab01;打印(lab01.sum_digits(10))@hck007$python-c'导入lab01;打印(lab01.sum_digits(10))
为什么在这里使用eval()
?一个简单的int()
调用不就是这样吗?此外,除非绝对必要,否则请不要以图像形式共享信息。见:。