Python程序不接受十进制原始输入

时间:2012-03-28 13:27:03

标签: python floating-point raw-input

我正在开发小型python工资单项目,您可以在其中输入员工姓名,工资和工时。当我输入工资输入的小数时,由于我的异常处理,我得到“无效输入”。为什么小数被返回为无效?此外,如何循环此程序,以便它保持相同的3个问题,直到用户键入“完成”? 任何帮助将不胜感激! 谢谢!

import cPickle

def getName():
    strName="dummy"
    lstNames=[]
    strName=raw_input("Enter employee's Name: ")
    lstNames.append(strName.title() + " \n")


def getWage():
    lstWage=[]
    strNum="0"
    blnDone=False
    while blnDone==False: #loop to stay in program until valid data is entered
        try:
            intWage=int(raw_input("Enter employee's wage: "))
            if intWage >= 6.0 and intWage <=20.0:
                lstWage.append(float(strNum)) #convert to float
                blnDone=True
            else:
                print "Wage must be between $6.00 and $20.00"
        except(ValueError): #if you have Value Error exception.  Explicit on error type
            print "Invalid entry"


def getHours():
    lstHours=[]
    blnDone=False
    while blnDone==False: #loop to stay in program until valid data is entered
        try:
            intHrs=int(raw_input("Enter number of hours worked: "))
            if intHrs >= 1.0 and intHrs <=60.0:
                blnDone=True
            else:
                print "Hours worked must be 1 through 60."
        except(ValueError): #if you have Value Error exception.  Explicit on error type
            print "Invalid entry"

def getDone():
    strDone=""
    blnDone=False
    while blnDone==False:
        try:
            srtDone=raw_input("Type \"DONE\" if you are finished entering names, otherwise press enter: ")
            if strDone.lower()=="done":
                blnDone=True
            else:
                print "Type another empolyee name"
        except(ValueError): #if you have Value Error exception.  Explicit on error type
            print "Invalid entry"


##### Mainline ########

strUserName=getName()
strWage=getWage()
strHours=getHours()
srtDone1=getDone()

5 个答案:

答案 0 :(得分:3)

以下是它的核心:

>>> int("4.3")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '4.3'

如果字符串不是整数,则无法将字符串转换为整数。因此,当您执行intWage=int(raw_input("Enter employee's wage: "))时,它会抛出ValueError。也许您应该将其直接转换为float

答案 1 :(得分:2)

因为您要将输入转换为int

intWage=int(raw_input("Enter employee's wage: "))

答案 2 :(得分:1)

您假设工资是一个整数,根据定义,它没有小数位。试试这个:

intWage=float(raw_input("Enter employee's wage: "))

答案 3 :(得分:0)

错误w / Floats

正如其他人之前所说,你假设输入将是一个浮点数。使用float()eval()代替int()

intWage = float(raw_input("Enter employee's wage: "))

或使用input()代替int(raw_input())

intWage = input("Enter employee's wage:")

两者都将完成同样的事情。哦,至少将intWage更改为floatWage,甚至更好,不要使用匈牙利表示法。

代码

至于你的代码,我做了几件事:

  • 使用break和/或return来终止循环,而不是跟踪布尔值(这是breakcontinue语句的全部目的)
  • intWage更改为floatWage
  • 以更简洁的方式重写数字比较(x <= y and x >= z可写为z >= x >= y
  • 添加了退货声明。除非你想None分配给strUserNamestrWagestrHours
  • ,否则我不明白为什么你没有自己动手。
  • 在询问员工的详细信息时,根据您的要求添加了一个循环。
  • 修改getDone()以使用循环。

import cPickle

def getName():
    strName = "dummy"
    lstNames = []
    strName = raw_input("Enter employee's Name: ")
    lstNames.append(strName.title() + " \n")
    return strName

def getWage():
    lstWage = []
    strNum = "0"
    while True:                                                #Loop to stay in program until valid data is entered
        try:
            floatWage = float(raw_input("Enter employee's wage: "))
            if 6.0 <= floatWage <= 20.0:
                lstWage.append(floatWage)
                return floatWage
            else:
                print "Wage must be between $6.00 and $20.00"
        except ValueError:                                     #Catches ValueErrors from conversion to float
            print "Invalid entry"

def getHours():
    lstHours = []
    while True:                                                #loop to stay in program until valid data is entered
        try:
            intHrs=int(raw_input("Enter number of hours worked: "))
            if 1.0 <= intHrs <= 60.0:
                return intHrs
            else:
                print "Hours worked must be 1 through 60."
        except ValueError:                                     #Catches ValueErrors from conversion to int
            print "Invalid entry"

def getDone():
    strDone = ""
    while True:
        srtDone = raw_input('Type "DONE" if you are finished entering names, otherwise press enter: ')
        if strDone.strip().lower() == "done":
            return True
        else:
            print "Type another empolyee name"

while not getDone():
    strUserName = getName()
    strWage = getWage()
    strHours = getHours()

def getName(): strName = "dummy" lstNames = [] strName = raw_input("Enter employee's Name: ") lstNames.append(strName.title() + " \n") return strName def getWage(): lstWage = [] strNum = "0" while True: #Loop to stay in program until valid data is entered try: floatWage = float(raw_input("Enter employee's wage: ")) if 6.0 <= floatWage <= 20.0: lstWage.append(floatWage) return floatWage else: print "Wage must be between $6.00 and $20.00" except ValueError: #Catches ValueErrors from conversion to float print "Invalid entry" def getHours(): lstHours = [] while True: #loop to stay in program until valid data is entered try: intHrs=int(raw_input("Enter number of hours worked: ")) if 1.0 <= intHrs <= 60.0: return intHrs else: print "Hours worked must be 1 through 60." except ValueError: #Catches ValueErrors from conversion to int print "Invalid entry" def getDone(): strDone = "" while True: srtDone = raw_input('Type "DONE" if you are finished entering names, otherwise press enter: ') if strDone.strip().lower() == "done": return True else: print "Type another empolyee name" while not getDone(): strUserName = getName() strWage = getWage() strHours = getHours()

break

的示例

循环中的continue语句(breakfor)终止循环并跳过所有'else'子句(如果有的话)。

while语句跳过循环中的其余代码,继续循环,就好像什么也没发生一样。

continue构造中的else子句在循环耗尽所有项目并正常退出时执行其代码块,即,当它没有被for...else或其他东西终止时。 / p>

break

答案 4 :(得分:0)

尝试使用

intWage=int(float(raw_input("Enter employee's wage: ")))

这将接受十进制数作为输入。