Python程序循环issu

2024-04-23 19:48:17 发布

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

我正在做一个Python程序。我的任务是要求用户输入公司的工资单信息。设置一个循环,在用户输入“DONE”之前继续询问信息。为每位员工问三个问题:

  1. 名字和姓氏
  2. 本周工作时间(仅允许1-60小时)
  3. 小时工资(仅允许6.00-20.00)

这是我的密码:

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")

当我运行程序并输入信息时,它会打印:

"Error Enter the employee's first and last name:"

有人能帮我/指引我正确的方向吗?你知道吗


Tags: the用户程序loop信息inputifemployee
3条回答

您比较的是字符串,而不是数值。因为"20" < "6"每个字符串将满足两个条件之一并打印Error。你知道吗

  1. 复习你的课堂材料;学会识别应用程序的适当数据类型,并使用该数据类型。在这种情况下,您需要将输入转换为int,并处理数值。你知道吗
  2. 练习增量编程:在添加更多代码之前,先使用几行代码。在这个例子中,您已经过了两步的工作代码,这使您的调试复杂化。你知道吗
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

如前一篇文章所述,不能比较字符串。你能做的就是把它们转换成整数,然后进行比较。你知道吗

最后的要求

Set up a loop that continues to ask for information until the user enters "DONE"

在用户回答所有问题后,您只能在应用程序中执行一次。我不知道你是不是有意的?如果您希望用户能够在任何时候退出应用程序,您可以像下面我所做的那样重新考虑代码

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 

以上代码中添加了注释,请阅读以获得澄清。你知道吗

相关问题 更多 >