[英]Python program not accepting decimal raw input
I am working on small python payroll project where you enter employee name, wage, and hours worked. 我正在研究小型python薪资项目,您在其中输入员工姓名,工资和工作时间。 When I enter decimals for the wage input, I am getting "invalid entry" because of my exception handling. 当我为工资输入输入小数时,由于我的异常处理,我得到“无效输入”。 Why are decimals being returned as invalid? 为什么小数返回无效? Also, how can I loop this program so that it keeps the same 3 questions until the user types "Done"? 另外,如何循环该程序,以便在用户键入“完成”之前,它保持相同的3个问题? Any help will be greatly appreciated! 任何帮助将不胜感激! Thanks! 谢谢!
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()
Here's the core of it: 这是它的核心:
>>> int("4.3")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '4.3'
You can't convert a string to an integer if it's not an integer. 如果字符串不是整数,则不能将其转换为整数。 So when you do intWage=int(raw_input("Enter employee's wage: "))
it throws the ValueError
. 因此,当您执行intWage=int(raw_input("Enter employee's wage: "))
它将引发ValueError
。 Perhaps you should convert it directly to float
. 也许您应该将其直接转换为float
。
因为您要将输入转换为int
:
intWage=int(raw_input("Enter employee's wage: "))
You are assuming that the wage is an integer, which by definition does not have a decimal place. 您假设工资是一个整数,根据定义,该整数没有小数位。 Try this: 尝试这个:
intWage=float(raw_input("Enter employee's wage: "))
Try using 尝试使用
intWage=int(float(raw_input("Enter employee's wage: ")))
This will accept a decimal number as input. 这将接受一个十进制数字作为输入。
As others said before, you are assuming the input will be a float. 正如其他人之前所说,您假设输入将是浮点型的。 Either use float()
or eval()
instead of int()
: 使用float()
或eval()
代替int()
:
intWage = float(raw_input("Enter employee's wage: "))
Or use input()
instead of int(raw_input())
: 或者使用input()
代替int(raw_input())
:
intWage = input("Enter employee's wage:")
Both will accomplish the same thing. 两者将完成同一件事。 Oh, and change intWage
to floatWage
atleast, or even better, don't use Hungarian Notation. 哦,改变intWage
到floatWage
ATLEAST,甚至更好,不要使用匈牙利命名法。
As for your code, I did a couple of things: 至于您的代码,我做了两件事:
break
and/or return
to terminate loops instead of keeping track of booleans (that's the whole purpose of the break
and continue
statements) 使用break
和/或return
来终止循环,而不是跟踪布尔值(这是break
和continue
语句的全部目的) intWage
to floatWage
将intWage
更改为floatWage
x <= y and x >= z
can be written as z >= x >= y
) 以更简洁的方式重写数字比较( x <= y and x >= z
可以写成z >= x >= y
) None
to strUserName
, strWage
and strHours
) 我不明白为什么您不自己放置它们,除非您想将None
分配给strUserName
, strWage
和strHours
) getDone()
to work w/ the loop. 修改了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()
break
and continue
break
并continue
的示例 The break
statements inside a loop ( for
and while
) terminate the loop and skip all 'else' clauses (if there are any). 循环内的break
语句( for
和while
)终止循环并跳过所有“ else”子句(如果有的话)。
The continue
statements skips the rest of the code in the loop and the continues the loop as if nothing happened. 在continue
语句跳过其余代码中环和继续循环,仿佛什么都没有发生。
The else
clause in a for...else
construct, executes its code block when the loop exhausted all the items and exited normally, ie, when it's not terminated by break
or something. for...else
构造中的else
子句在循环用尽所有项目并正常退出时(即当它没有被break
或其他东西终止)时执行其代码块。
for no in range(2, 10):
for factor in range(2, no):
if no % factor == 0:
if factor == 2:
print "%d is even" % no
continue
# we want to skip the rest of the code in this for loop for now
# as we've already done the printing
print "%d = %d * %d" % (no, factor, n/x)
break
# We've asserted that the no. isn't prime,
# we don't need to test the other factors
else:
# if 'break' wasn't called
# i.e., if the loop fell through w/o finding any factor
print no, 'is a prime number'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.