Member Avatar for Hatz2619

Sorry guys, I'm a rookie at the whole Python thing so please forgive me if the following questions are easily answered.

I'm working on my final project for class and I'm just stuck. I have no clue what's going on with this program. It isn't running properly in IDLE at all. Could someone please look it over and give me insight as to what the problems are with this program? Keep in mind I've only been dealing with Python for approximately 3 and a half months at a rate of one class a week.

##2.  Ask the user to enter payroll information for the company.  Set up a loop that continues to
##ask for information until they enter “DONE”.  For each employee ask three questions:
##o	name (first & last)
##o	hours worked this week (only allow 1 through 60)
##o	hourly wage (only allow 6.00 through 20.00)
##VALIDATE the hours worked and the hourly wage, and make sure a name is entered.

salaries=[]
name="Dummy"
hours="0"
wage="0"
while name.title() !="Done":
    name=raw_input("Enter the first and last name of the employee: ")
    if name.title()=="Done":
        if salaries.append(name.title()):
            break
    else:
        while hours<1 or hours>60:
            hours=int(raw_input("Enter the number of hours a week worked: "))
            if hours<1 or hours>60:
                print "Error.  Please enter a number between 1 and 60: "
        while wage<6 or wage>20:
            wage=int(raw_input("Enter the hourly wage of the employee: "))
            if wage<0 or wage>20:
                print "Error.  Please enter a number between 6 and 20: "
    if hours <=40:
        grossPay=hours*wage
    else:
        grossPay=((hours-40)*(wage*1.5))+(40*wage)
    print name
    print hours
    print wage
    print grossPay


##3.  Calculate each employee’s pay, and write it out to a sequential file.   Be sure to include file
##I/O error handling logic.   
##o	Include only the weekly pay
##o	Weekly pay is calculated: 
##	For (1-40 hours) it is hourly rate * hours worked
##	For (41-60 hours) it is (hours worked – 40) * (hourly rate * 1.5) 
##+ hourly rate * 40

try:
    salariesWage=open("PAY.txt", "w")
    salariesList.writelines(salaries)
    salariesWage.close()
except(IOError):
    print "Error writing to file list"



##4.  After all the employees are entered, read in the sequential file into a list named PAY for
##the weekly pay of each employee.  Sort the list.  Now print the lowest, highest, and average
##weekly pay for the week.

try:
    employeeWage=open("PAY.txt", "r")
    employeeList.readlines(salaries)
    employeeWage.close()
except(IOError):
    print "Error writing to file list"

Each step of what the program is supposed to do is commented out and in red.

To give a summary of what I'm having issues with:

1. The loop won't work correctly. I can loop through all three questions ONE time and that's it. When I enter a second batch of data (name, hours, wage), it only lets me input a new name then automatically assigns the previous hours and wage.

2. I can't write to a txt file properly. As of right now, I'm getting an error concerning a list not defined. Before that it was writing a PAY.txt file but it was totally blank.

3. Since I can't write to a txt file, I can't read and sort either.

Any help would be greatly appreciated.

One last thing to keep in mind is that I'm using v.2.5.4 so any new tricks in the newer versions need to be ruled out. Needs to be done in this version.

Thanks in advance.

First of all, you could get some better organization by using functions.
Here's a structure I would find easy to work with:

get_name() #Gets and returns the first and last name, validating them first

get_hours() #Gets and returns the hours worked for the week, with validation

get_wage() #Get and return the hourly wage, with validation

input_loop() #Loop until "DONE" is entered, using above three functions; return a list of tuples: (name, hours, rate)

calculate_pay(rate, hours) #Calculate and return the week's pay based on the rules.

save_file(list_of_tuples) #Saves the file with data returned from above. It may look something like this:

def saveFile(employees):
    try:
        fh = open("pay.txt", "w")
    except:
        #Failure to open file. Handling core here
        return
    
    for emp in employees:
        name, hours, rate= emp
        pay = calculatePay(hours, rate)
        try:
            fh.write(name + " " str(pay) + "\n")
        except:
           #Handling code
           continue
        
   fh.close()
Member Avatar for Hatz2619

First of all, you could get some better organization by using functions.
Here's a structure I would find easy to work with:

get_name() #Gets and returns the first and last name, validating them first

get_hours() #Gets and returns the hours worked for the week, with validation

get_wage() #Get and return the hourly wage, with validation

input_loop() #Loop until "DONE" is entered, using above three functions; return a list of tuples: (name, hours, rate)

calculate_pay(rate, hours) #Calculate and return the week's pay based on the rules.

save_file(list_of_tuples) #Saves the file with data returned from above. It may look something like this:

def saveFile(employees):
    try:
        fh = open("pay.txt", "w")
    except:
        #Failure to open file. Handling core here
        return
    
    for emp in employees:
        name, hours, rate= emp
        pay = calculatePay(hours, rate)
        try:
            fh.write(name + " " str(pay) + "\n")
        except:
           #Handling code
           continue
        
   fh.close()

Thanks for the input. Two things. First off, I didn't use functions because I'm not very comfortable with them. I've only had a week of training on them and then we got this project so I haven't used them a whole lot before this. I'm more used to using loops so if I can answer the questions in the project that way, I'd prefer that.

Second, that section of code you wrote. If I were to use that would I be appending to my existing code somewhere or just using that? I tried running that in IDLE but comes back with an error at "str(pay)"


I guess what I'm wondering is can you or anyone tell me what's wrong with my existing code as opposed to rebuilding it from the ground up?

This should get you started, I have created a small program which makes three lists, one for names, hours and wages. The while loop works as well. The problem with your program was that I think you weren't defining variables before using them, for example you didn't create a salariesList or an employeeList before using them. Give a shout if you need more pointers.

#create three lists to store the information
names = []
hours = []
wages = []
#initiate loop
while True:
    name = raw_input("Enter the first and last name of the employee: ")
    names.append(name)
    if name == "Done":
        break
    else:
        hour = raw_input("Enter the number of hours a week worked: ")
        hours.append(hour)
        wage = raw_input("Enter the hourly wage of the employee: ")
        wages.append(wage)
        print "names:", names
        print "hours:", hours
        print "wages:", wages
#end program if user enters "Done"
else:
    pass

Actually ignore that last

else:
    pass

as it doesn't do anything

I can loop through all three questions ONE time and that's it.

while hours<1 or hours>60:
            hours=int(raw_input("Enter the number of hours

If you entered 42 hours on the first pass, then hours still equals 42 and you will not enter the while loop. See Shibby's snippet. Use one infinite while() loop, to get all of the data, and break out of the loop when "Done" is entered.

try:
    salariesWage=open("PAY.txt", "w")
    salariesList.writelines(salaries)
    salariesWage.close()
except(IOError):
    print "Error writing to file list"
...
try:
    employeeWage=open("PAY.txt", "r")
    employeeList.readlines(salaries)
    employeeWage.close()
except(IOError):
    print "Error writing to file list"

Upon initial inspection I see that you're opening PAY.txt as salariesWage and then employeeWage but then trying to read/write as salariesList and employeeList respectively. That should fix your reading/writing problem...

I also notice that you initialize the variables hour and wage as "0" which means you want those variables to be strings containing the character zero. Once inside your loop you try comparing the values of these variables numerically, so I think that for initialization before the loop you'd actually want hours = wage = 0 . This might not have caused any problems but it's just for completeness' sake.

As far as not being able to input new hours and wage it is due to the fact that you don't reset the values of the variables hour and wage to 0 before the loop restarts. So when the logic hits the line that says: while hours<1 or hours>60: , it will not enter the code block and ask the user for input. To fix this issue just reassign hours = wage = 0 either at the end or the very beginning of your main while loop.

Oh and one last thing... you never add anything to your salaries list unless the user enters 'Done' to quit the program. You should be doing that at the end of your while loop before you reinitialize the wage and hours variables to 0

Upon initial inspection I see that you're opening PAY.txt as salariesWage and then employeeWage but then trying to read/write as salariesList and employeeList respectively. That should fix your reading/writing problem...

Also, that block of code should go under the while loop as well in order to write each employee. Hopefully, the reason for this is obvious. So you will have a while loop, it will do everything until "Done" is entered, which will trigger a break() statement, and then you can print something like "Bye bye" if you want to show that you have exited the loop.

One last note is that employeeWage.readlines(salaries) should actually be salaries = employeeWage.readlines()

Member Avatar for Hatz2619

Thanks for all the help guys. I really appreciate it. Ironically, I got the loop working properly early this morning before I even checked this thread and I ended up kinda doing what jlm699 talked about. I didn't reinitialize the loop. Hours of work when all I had to do was put two simple lines of code under the name=raw_input.

Now just to work on the writing and reading portion. I'll check over the other stuff that everyone has written. Once again, thanks guys.

Member Avatar for Hatz2619

Projects been completed. Thanks for the help all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.