Python返回功能对我不起作用

时间:2013-11-27 23:11:32

标签: python

我有以下代码:

#gets the filename from the user
b= input("Please enter a file name to be opened: ")
a = (b+".txt")
#main data storage and other boolean options
data =[]

result1 =[]
on = True 
#File reading in main body with try and except functionality.
try:
    check = open(a, 'r')
    line =check.readlines()
    for items in line:
        breakup= items.split()
        number, salary, position, first, oname1, oname2, last = breakup
        data.append(tuple([last, first + ' ' + oname1 + ' ' + oname2, number, position, salary]))
except IOError as e :
        print("Failed to open", fileName)

#Employee creation function, takes the line and stores it in the correct position.
def employee_creation():

    result = [((item[0] +", "+ item[1]).ljust(30), int(item[2]), item[3].ljust(15), int(item[4])) for item in data]
    for items in result:
            result1.append((items[0][0:30], format(items[1], "^5d"), items[2][0:15], "£"+format((items[3]),"<8d")))

    return(result)

employee_creation()
print(result)
while on == True:
    print("Please select what option you would like to use to search for employees:")
    option = int(input("""
          1 - Salary (X to X)
          2 - Job Titlle
          3 - Name, Payroll Number
                    :"""))

    if option == 1:
        start = input("What range would you like to start from: ")
        end = input("What is the maximum range you would like :")
        for items in result:
            print(items[3])
            if items[3]>start and items[3]<end:
                print(items)
            else:
                print("No employees with this information can be found")
                on= False
    else:
        on= False

但是我的def employee_creation()实际上并没有返回结果。我需要它使它成为一个全局变量,以便我可以使用它来针对数据启动个人查询。

有人能看出为什么它不起作用吗?

1 个答案:

答案 0 :(得分:1)

无需使用邪恶的全局变量。您忘记将函数的结果存储到另一个变量。

def employee_creation():

    result = [((item[0] +", "+ item[1]).ljust(30), int(item[2]), item[3].ljust(15), int(item[4])) for item in data]
    for items in result:
            result1.append((items[0][0:30], format(items[1], "^5d"), items[2][0:15], "£"+format((items[3]),"<8d")))

    return result # no need for () here

result = employee_creation() # store the return value of your function
print(result)