Python 3.x.我试图创建一个工资单程序,接受每个员工工作小时数的输入,并将其乘以预定的工资。如果用户输入无效输入,则错误陷阱,例如" abc"用了几个小时。然而,它不会接受浮动值。我知道isdigit()不适用于小数,因为"。"在isdigit()中返回一个false值。如何修改此程序以接受int和float值作为有效输入?
#! python3
#This is a program to calculate payroll expenses.
employees = ['Oscar', 'Judy', 'Sandra', 'Tino', 'Andres', 'Rich', 'Matt', 'Daniel', 'Natalie', 'Elena']
employeeHourlyPay = [14.5, 14.5, 13.5, 13.0, 13.0, 11.0, 11.0, 10.0, 9.0, 10.0]
employeeHours = []
totalPay = []
#Iterate through employees and ask for hours worked. Program will check for
#valid digit inputs, and prompt you to only enter digits when anything else
#is entered as input.
#****Fix to accept decimals****#
for i in employees:
while True:
print('Enter hours for', i , ':')
x = str(input())
if x.isdigit():
employeeHours.append(float(x))
break
else:
print('Please use numbers or decimals only.')
continue
#***End Fix***
#Calculate pay per employee and add to list.
for i, j in zip(employeeHourlyPay, employeeHours):
totalPay.append(i * float(j))
#Display pay per employee by iterating through employees and totalPay.
for i, j in zip(employees, totalPay):
print(i + "'s pay is", str(j))
#Calculate and display total payroll by summing items in totalPay.
print('Total Payroll: ' + str(sum(totalPay)))
答案 0 :(得分:2)
python中常见的习惯用法是EAFP(比请求更容易要求宽恕),这意味着基本上只是尝试转换并处理异常,例如:
x = str(input())
try:
employeeHours.append(float(x))
break
except ValueError:
print('Please use numbers or decimals only.')
continue
答案 1 :(得分:0)
最好说你很抱歉而不是要求获得许可......只是尝试从输入中获得float
并且很好......如果你得到例外,那是因为它不是浮动的:
for i in employees:
while True:
print('Enter hours for', i, ':')
try:
x = float(input())
print("You entered x=%s" % x)
employeeHours.append(x)
break
except ValueError:
print('Please use numbers or decimals only.')
continue