尝试制作一个应用程序,减去所有在易趣上出售的物品的费用
NetSale = 0
ListFee = 0
PayPalFee = 0
ShippingFee = 0
def int_or_float(i):
try:
return int(i)
except ValueError:
return float(i)
NetSale = input("What is the Net Sale? ")
ListFee = input("What is the List Fee? ")
PayPalFee = input("What is the PayPal Fee? ")
ShippingFee = input("What is the Shipping Cost? ")
int_or_float(NetSale)
int_or_float(ListFee)
int_or_float(PayPalFee)
int_or_float(ShippingFee)
Profit = NetSale-ListFee
print(Profit)
当我运行应用程序时,我得到一个类型错误,因为它试图减去两个字符串。如果这些变量包含int或float,如何使其相减
可以在请求用户输入时进行int/float的转换。下面的代码应该可以做到这一点
在Python中,将不可变对象传递给函数将按值传递,而不是按引用传递。在
int_or_float()
函数中将值强制转换为int()
或float()
,但不会在代码的主流中捕获它。因此,NetSale
变量不会被int_or_float()
函数修改。它仍然是一根弦。只需在函数调用之后捕获它:相关问题 更多 >
编程相关推荐