我的 .py 代码有什么问题,如何在 linux 终端中将其发送到 运行?

What is wrong with my .py code and how do I get this to run in a linux terminal?

def WCTemp(temp,velocity):
    '''
    >>> WCTemp(32,10)
    23.44
    >>> WCTemp(80,30)
    82.07
    '''
    #place code here
    v = velocity**0.16
    r = 35.74 + 0.6125 * temp - 35.75 * v + 0.4275 * temp * v
    a = "%.2f" % r
    return (a)

我希望能够打开终端,转到这个 test.py 文件所在的目录,键入 "python -i test.py",然后能够键入 "WCTemp(32,10)",然后得到答案23.44.

但是,我不断收到此错误:

Traceback (most recent call last):
File "hw1.py", line 15, in <module>
print ("%.2f" % WCTemp(temp,velocity))
NameError: name 'temp' is not defined

为了从命令行(即 >>> python3 file.py)运行 这段代码,您需要将它保存为一个模块(file.py),并将其重构为以下内容:

def WCTemp(temp,velocity):
    '''
    >>> WCTemp(32,10)
    23.44
    >>> WCTemp(80,30)
    82.07
    '''
    #place code here
    v = velocity**0.16
    return 35.74 + 0.6125 * temp - 35.75 * v + 0.4275 * temp * v

if __name__ == "__main__":
    print ("%.2f" % WCTemp(32, 10))

但首先,您需要在打印语句中为 tempvelocity 参数传递值。否则,你的函数没有什么可计算的!

只需将 print 行更改为:

print ("%.2f" % WCTemp(32,10))

和 运行 您的程序具有:python file.py

其中 file.py 是包含代码的文件名。

我猜你正试图这样做。

def WCTemp(temp,velocity):
    v = velocity**0.16
    r = 35.74 + 0.6125 * temp - 35.75 * v + 0.4275 * temp * v
    print ("%.2f" % r)


WCTemp(32,10) 

运行 教科书:

def WCTemp(temp,velocity):
    '''
    >>> WCTemp(32,10)
    '23.44'
    >>> WCTemp(80,30)
    '82.07'
    '''
    #place code here
    v = velocity**0.16
    r = 35.74 + 0.6125 * temp - 35.75 * v + 0.4275 * temp * v
    a = "%.2f" % r
    return (a)

if __name__ == "__main__":
    import doctest
    doctest.testmod()

传递 -v 标志以查看输出:

~$ python   test.py  -v
Trying:
    WCTemp(32,10)
Expecting:
    '23.44'
ok
Trying:
    WCTemp(80,30)
Expecting:
    '82.07'
ok
1 items had no tests:
    __main__
1 items passed all tests:
   2 tests in __main__.WCTemp
2 tests in 2 items.
2 passed and 0 failed.

如果您已将其保存在问题中的文件中 python -i test.py 将完全按照您的要求工作:

test.py:

def WCTemp(temp,velocity):
    '''
    >>> WCTemp(32,10)
    23.44
    >>> WCTemp(80,30)
    82.07
    '''
    #place code here
    v = velocity**0.16
    r = 35.74 + 0.6125 * temp - 35.75 * v + 0.4275 * temp * v
    a = "%.2f" % r
    return (a)

~$ python -i v.py
>>> WCTemp(32,10)
'23.44'