pythontkinter如何识别一个空的float并用z替换它

2024-09-30 10:31:35 发布

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

现在我正在计算以下条目的总数。如果我不给一个输入,我希望它认为输入为零,但是如果没有输入,就没有总的计算。一个简单的变量==''检测

#getting the quantity of fries etc

coF=float(Fries.get()) #cost of fries
coD=float(Drinks.get())
coFilet=float(Filet.get())
coBurger=float(Burger.get())
coChicken=float(Chicken_Burger.get())
coCheese=float(Cheese_Burger.get())

#computation

costofFries=coF * 300 #store whatever is entered in widget
costofDrinks=coD * 300
costofFilet=coFilet * 200
costofBurger=coBurger * 100
costofChicken=coChicken * 150
costofCheese=coCheese * 100

#total calculation

paytax=((costofFries+costofDrinks+costofFilet+costofBurger+costofChicken
                            +costofCheese)*0.2)
TotalCost=(costofFries+costofDrinks+costofFilet+costofBurger+costofChicken
                            +costofCheese)
Ser_Charge=((costofFries+costofDrinks+costofFilet+costofBurger+costofChicken
                            +costofCheese)/99)

现在,如果我输入所有的值,那么我就得到正确计算的总数,如果我不输入值,它就计算总数。请建议


Tags: ofgetfloatcodburger总数friescof
1条回答
网友
1楼 · 发布于 2024-09-30 10:31:35

你能做到的

if Fries.get(): 
    cof = float(Fries.get()) 
else: 
    cof = 0

或与if/else一起使用特殊结构

cof = float(Fries.get()) if Fries.get() else 0

但是有人可以放置文本或不正确的浮点,所以最好使用try/except来捕获它

try:
    coF = float(Fries.get())
except ValueError:
    coF = 0

相关问题 更多 >

    热门问题