为什么我的python代码抛出ValueErrors异常?

Why my python code throws ValueErrors exception?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
while RUN2:
    chose = int(input('Type the option number from 1 to 6:'))

    if chose == 1:
        print(grossPayMsg())
        print("Your gross pay is", grosspay(workhour, hourlywage))      

    elif chose == 2:    
        print(withHoldingsMsg())
        print("Your withholdings is", withhd(workhour, hourlywage))    

    elif chose == 3:  
        print(federalTaxMsg())
        print("Your Federal Tax is", fedtax(workhour, hourlywage))

    elif chose == 4:    
        print(marylandTaxMsg())
        print("Your Federal Tax is", mdtax(workhour, hourlywage))

    elif chose == 5:    
        print(netPayMsg())
        print("Your Federal Tax is", net(workhour, hourlywage))

    elif chose == 6:
        print ("Thank you for using. Goodbye!")
        RUN2 = False

    else:
        print("/////// Invalid option number ///////")

=========================================================

问:我怎样才能避免在按下回车键而不是输入选项号时出现如下值错误?我知道有些用户可以故意或意外地点击enter。有什么话可以避免吗?我只学了int(input)或input…

ValueError:无法将字符串转换为float

valueError:基为10的int()的文本无效:""

=====================

提前非常感谢你……


您可以通过更改此代码来删除none

1
2
3
if chose == 1:
        print(grossPayMsg())
        print("Your gross pay is", grosspay(workhour, hourlywage))

1
2
3
if chose == 1:
            grossPayMsg() # print is removed because when you use print it prints the return value of grossPayMsg()
            print("Your gross pay is", grosspay(workhour, hourlywage))

您可以使用strng.isnumeric()函数检查输入的字符串是否为数字。然后转换成float,储存在workhourhourlywage中。

1
2
3
strng = input("What's your hours worked?:")
if strng.isnumeric() :
  workhour = float(strng)