代码显示这是一个错误类型bu

2024-06-08 17:11:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码。你知道吗

#!/usr/bin/python

from optparse import OptionParser   #import the OptionParser object from this module

parser = OptionParser()

parser.add_option("-f", "--first", dest="meal", help="prix repas", type="float")  
parser.add_option("-s", "--second", dest="tip", help="le tip", type="float")
parser.add_option("-t", "--third", dest="tax", help="tax", type="float")


(options, args) = parser.parse_args() 

tax_value = options.meal * options.tax
meal_with_tax = tax_value + options.meal
tip_value = meal_with_tax * tip

if not (options.meal and options.tip): 
parser.error("You need to supply an argument for -s")

print "le prix du repas est '{}'.".format(options.meal)
print "Le tip est de '{}'.".format(options.tip)
print "Le tip est de '{}'.".format(options.tip)

每次我用下面的命令行运行它

./tip_re1_arg.py -s 5 2 3

我有个错误tax_value = options.meal * options.tax TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

为什么?就类型而言,我似乎做得都对。还是我?你知道吗

对不起,我对Python还只是个初学者。你知道吗


Tags: addparservaluetypehelpfloatdestoptions
2条回答

您已经显式配置了解析器,以期望参数作为选项:

./tip_re1_arg.py -f 5 -s 2 -t 3

./tip_re1_arg.py  first 5  second 2  third 3

当前输入参数以args结束。你知道吗

运行时需要指定选项。换句话说:

./tip_re1_arg.py -f 5 -s 2 -t 3

解析器不会只接受3个未声明的选项并分配它们。现在,您可以直接使用输入参数数组(使用系统argv[1] 等等)。不过,这可能比将你的论点改为它们的实际含义(即-m/餐、-x/税、-t/小费)更不友好。你知道吗

不管怎么说,按您所说的方式,餐费和税金实际上并没有分配,所以是空的,这就给了您非类型错误。你知道吗

相关问题 更多 >