尝试用Python为ebay卖家制作应用程序

2024-09-28 21:55:20 发布

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

尝试制作一个应用程序,减去所有在易趣上出售的物品的费用

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,如何使其相减


Tags: orthe应用程序inputreturnisfloatwhat
2条回答

可以在请求用户输入时进行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)

在Python中,将不可变对象传递给函数将按值传递,而不是按引用传递。在int_or_float()函数中将值强制转换为int()float(),但不会在代码的主流中捕获它。因此,NetSale变量不会被int_or_float()函数修改。它仍然是一根弦。只需在函数调用之后捕获它:

NetSale = int_or_float(NetSale)
ListFee = int_or_float(ListFee)
PayPalFee = int_or_float(PayPalFee)
ShippingFee = int_or_float(ShippingFee)

相关问题 更多 >