比较Python 3中

时间:2017-12-05 22:23:34

标签: python python-3.x indexing tuples readfile

我的目标是显示员工的记录,工资在2个用户输入的值之间(以我的函数printTuple(data)中指定的格式)。到目前为止,我使用函数choice2()打开文件,在for循环中逐行读取,将行(这是一个字符串)转换为int,然后获取工资的索引,以便我可以将它与2个输入值(。之后我将该行作为变量在"记录"然后转到makeTuple将其转换为元组,然后最终在printTuple中以所需格式打印。

当我尝试运行choice2函数时,我收到一个错误:"本地变量' myTuple'在转让之前引用"。但是我需要将myTuple值更改为int才能将其与用户输入的值进行比较,因此我不确定如何解决此问题。

这是我的计划:

def makeTuple (employee):

    myTuple = employee.split(" ")
    (payroll, salary, job_title, *othernames, surname) = myTuple
    return(myTuple)

def printTuple (data):

    employee_str = "{:<15} {:20} {:<10} {:<15} £{:>1}"
    print(employee_str.format(data[-1]+ ",", " ".join(data[3:-1]), data[0], data[2], data[1]))

def choice1():

    op_1 = str(input("Please enter a Pay Roll number: "))
    file = open(path)
    lines = file.readlines()
    for line in lines:
        if op_1 in line:
            record = line.strip()
    myTuple = makeTuple(record)
    printTuple(myTuple)

def choice2():

    op_2a = int(input("Please enter a lower bound for the Salary :"))
    op_2b = int(input("Please enter a higher bound for the Salary :"))

    file = open(path)
    lines = file.readlines()
    for line in lines:
        myTuple[0] = int(myTuple[0])
        if myTuple[0] >= op_2a and myTuple[0] <= op_2b:
            myTuple[0] = myTuple[0]
            record = line.strip()        
    myTuple = makeTuple(record)
    print(myTuple)

get_file = input(str("Please enter a filename: "))    
path = get_file + ".txt"

try:
    f = open(path)
except IOError:
    print('The file could not be opened.')
    exit()

for line in iter(f):
    record = line.strip()
    myTuple = makeTuple(record)
    printTuple(myTuple)


print("\n\nDisplay full details of an Employee with a given payroll number     enter:     '1'")
print("Display all employees with a salary within a specified range, enter:           '2'")
print("Display the first and last name of all employees with a job title,     enter:  '3'")
print("Quit Program:                                                              '4'")

choice = int(input("Choose an option from 1-4: "))

while choice != 1 and choice != 2 and choice != 3 and choice != 4:

    print("Incorrect Value, please choose a number from 1-4")
    print("\n\nDisplay full details of an Employee with a given payroll     number enter:     '1'")
    print("Display all employees with a salary within a specified range,     enter:       '2'")
    print("Display the first and last name of all employees with a job     title, enter:  '3'")
    print("Quit Program:                                                                  '4'")

    choice = int(input("Choose an option from 1-4: "))

if choice == 1:
choice1()
if choice == 2:
choice2()
if choice == 3:
choice3()
if choice == 4:
exit()

这是我正在阅读的文本文件:

12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
12349 30000 Wizard Harry Potter
12350 15000 Entertainer Herschel Shmoikel Krustofski
13123 75000 Consultant Zlatan Ibrahimovic
13124 150000 Manager Gareth Southgate
13125 75000 Manager Juergen Klopp
13126 35000 Lecturer Mike T Sanderson
13127 200000 Entertainer Adele Laurie Blue Adkins
13128 50 Timelord Peter Capaldi
13129 250000 Entertainer Edward Christopher Sheeran
13130 32000 Secretary Wilma Flintstone

提前感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您的错误消息(local variable myTuple referenced before assignment)指出了所需的解决方案。我有:

  • 重新排序(record = line.strip()myTuple = makeTuple(record)到循环顶部)
  • 重命名了一些变量(myTuple不是很具描述性,无论如何它实际上都是一个列表,更好的命名使代码更容易阅读和推理)
  • 大量评论(我通常不会评论我自己的代码,更多的是作为我已经完成的事情和原因的指示)

以下是choice2

的更新代码
def choice2():

    lower_bound = int(input("Please enter a lower bound for the Salary :"))  # Renamed for clarity
    upper_bound = int(input("Please enter a higher bound for the Salary :"))  # Renamed for clarity

    # The following two lines are repeated multiple times, you should probably read
    # the file once and store into a list (or better yet a dictionary
    # keyed with pay roll number) and pass it into the function.
    file = open(path)
    lines = file.readlines()

    for line in lines:
        record = line.strip()
        employee_details = makeTuple(record)  # Rename muTuple to employee_details
        # OR MORE SIMPLY employee_details = makeTuple(line.strip())

        # Now we have the variable we can work with it
        salary = int(employee_details[0])  # The only thing we do with the tuple is print it, so no need to modify it
        if salary >= lower_bound and salary <= upper_bound:
            # This does nothing, so deleted - myTuple[0] = myTuple[0]
            print(employee_details) # Or more likely you want to use your custom print function printTuple(employee_details)