python3:接受工资单程序的小数

2024-09-30 12:14:39 发布

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

python3.x。如果用户输入一个无效的输入,比如“abc”几个小时,它会正确地捕捉错误。但是它不接受浮点值。我知道isdigit()不适用于小数,因为“.”在isdigit()中返回假值。如何修改此程序以接受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)))   

Tags: andtoinforispayrollfloatpay
2条回答

python中的一个常见习惯用法是EAFP(请求原谅比请求许可更容易),意思是只需尝试转换它并处理异常,例如:

x = str(input())
try:
    employeeHours.append(float(x))
    break
except ValueError:
    print('Please use numbers or decimals only.')
    continue

与其请求允许,不如说对不起。。。试着从输入中得到一个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

相关问题 更多 >

    热门问题