[英]Trying to make app for ebay seller in Python
尝试制作一个可以扣除在Ebay上出售的商品的所有费用的应用。
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)
当我运行应用程序时,出现类型错误,因为它试图减去两个字符串。 我如何做到这一点,以便如果它们包含整数或浮点数,我可以减去这些变量?
在Python中,将不可变对象传递给函数将按值而不是按引用传递它们。 您可以将值转换为int_or_float()
函数中的int()
或float()
,但不要在代码的主流中将其捕获。 因此, int_or_float()
函数不会修改NetSale
变量。 它仍然是一个字符串。 就这样在函数调用之后捕获它:
NetSale = int_or_float(NetSale)
ListFee = int_or_float(ListFee)
PayPalFee = int_or_float(PayPalFee)
ShippingFee = int_or_float(ShippingFee)
可以在询问用户输入时完成向int / float的转换。 下面的代码应该可以解决问题。
NetSale = 0
ListFee = 0
PayPalFee = 0
ShippingFee = 0
def int_or_float(i):
try:
return int(i)
except ValueError:
return float(i)
NetSale = int_or_float(input("What is the Net Sale? "))
ListFee = int_or_float(input("What is the List Fee? "))
PayPalFee = int_or_float(input("What is the PayPal Fee? "))
ShippingFee = int_or_float(input("What is the Shipping Cost? "))
Profit = NetSale-ListFee
print(Profit)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.