尝试用Python为易趣卖家制作应用程序
正在尝试制作一个应用程序,该应用程序将从Ebay上出售的物品中扣除所有费用尝试用Python为易趣卖家制作应用程序,python,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 = inpu
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,如何使其相减?在Python中,将不可变对象传递给函数将按值传递,而不是按引用传递。在
int\u或\u float()
函数中,将值强制转换为int()
或float()
,但不会在代码的主流中捕获它。因此,NetSale
变量不会被int\u或\u float()
函数修改。它仍然是一根弦。只需在函数调用后捕获它,如下所示:
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)
您正在从
int\u或\u float()
函数返回值,但没有捕获它,因此您没有替换存储在四个变量中的字符串。只需将其更改为NetSale=int\u或\u float(NetSale)
同时允许int
和float
有什么意义?float
本身就足够了吗?我不确定。我是个初学者。float()是否适用于所有数字,而不仅仅是小数?一个小小的nit,将对象传递到函数中永远不会按值传递它们。它可能看起来是这样的,因为在函数内重新分配它们只是将函数内的引用指向不同的对象。对函数内部对象的修改在函数外部总是可见的,但当对象本身是不可变的,因为int
和float
是不可变的时,这是一个没有意义的点。感谢指针,我读了一些书,现在更好地掌握了python如何处理参数。我应该说传递不可变表就像传递值一样,因为修改它们的操作是无效的,而传递可变表就像传递引用一样,直到赋值。