[英]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.