我正在做一个Python程序。我的任务是要求用户输入公司的薪资信息。设置一个循环,继续询问信息,直到用户输入“ DONE”为止。对于每个员工,请问三个问题:
这是我的代码:
while True: #initiate loop
strNames = input("Enter the employee's first and last name:")
strHours = input("Enter total number of hours worked this week:")
strWage = input("Enter employee's hourly wage:")
if strNames =="DONE":
break #breaks loop
else:
if strHours < "1" or strHours > "60":
print("Error")
if strWage < "6" or strWage > "20":
print("Error")
当我运行程序并输入信息时,它会打印:
“错误输入员工的名字和姓氏:”
有人可以帮助我/指导我正确的方向吗?
答案 0 :(得分:0)
您已经比较了字符串,而不是数字值。自"20" < "6"
起,每个字符串将满足您的两个条件之一,并显示Error
。
int
并使用数字值。答案 1 :(得分:0)
如前一篇文章所述,您不能比较字符串。您可以做的是将它们转换为整数,然后进行比较。
最后一个要求
设置一个循环,继续询问信息,直到用户输入“完成”为止
用户回答所有问题后,您只需在应用程序中执行一次此操作。我不确定您是否打算这样做?如果您希望用户能够随时退出应用程序,则可以像下面所述那样重构代码
questions = ["Enter the employee's first and last name:",
"Enter total number of hours worked this week:",
"Enter employee's hourly wage:"]
var = ['strNames', 'strHours', 'strWage']
while True: #initiate loop
x = 0 # declare a variable for incrementing list 'var'
for q in questions:
var[x] = input(q)
if var[x].upper() =="DONE": # checking if the user entered 'DONE'
break # breaks inner for loop
x += 1 # increment list count by 1
try:
if int(var[1]) < 1 or int(var[1]) > 60:
print("\n>>> Hours worked this week error\n")
if int(var[2]) < 6 or int(var[2]) > 20:
print("\n>>> Hourly wage error\n")
except: # catches any exception errors
# if exception occurs, come in here and break out of loop
break # break while loop
注释已添加到上面的代码中,因此请阅读以进行澄清。
答案 2 :(得分:-1)
while True: #initiate loop
strNames = input("Enter the employee's first and last name: ")
if strNames =="DONE":
break #breaks loop
strHours = int(input("Enter total number of hours worked this week: "))
if strHours < 1 or strHours > 60:
print("Error 1")
break
strWage = int(input("Enter employee's hourly wage: "))
if strWage < 6 or strWage > 20:
print("Error 2")
break
if strNames =="DONE":
break #breaks loop