0

I am new to programming Python, learning mostly through "learn python the hard way." I recently wrote a script that will help me calculate the overtime earnings for my piece work employees. The script works, but it just doesn't look right to me. I would love input on how I could have saved myself some steps. I know using globals is taboo, but I could not figure out another way to get the answers outside those functions. Thank you!!

# THIS SCRIPT WILL CALCULATE THE NUMBER OF PAID HOURS, OVERTIME HOURS, PIECE RATE HOURS AND OVERTIME HOURS OWED TO AN EMPLOYEE.

number_of_straight_hours_worked = False
number_of_overtime_hours_worked = False
employee_travel_time = False
days_worked = False
employee_earnings = False
employee_hourly_rate = False
employee_overtime_rate = False

#Function to determine number of straight hours worked.
def straight_hours():
    global number_of_straight_hours_worked

    number_of_straight_hours_worked = float(number_of_straight_hours_worked)
    while number_of_straight_hours_worked == False:

        number_of_straight_hours_worked = raw_input("How many straight hours did the employee work?  ")

        try:
                int(number_of_straight_hours_worked)
        except ValueError:
            print("Must use a number")
            number_of_straight_hours_worked = False
        else:
            print ("Thank you.")
            #print number_of_straight_hours_worked

# Determines number of overtime hours.
def overtime_hours():
    global number_of_overtime_hours_worked

    number_of_overtime_hours_worked = float(number_of_overtime_hours_worked)
    while number_of_overtime_hours_worked == False:

        number_of_overtime_hours_worked = raw_input("How many overtime hours did the employee work?  ")

        try:
            int(number_of_overtime_hours_worked)
        except ValueError:
            print("Must use a number")
            number_of_overtime_hours_worked = False
        else:
            print ("Thank you.")
            #print number_of_overtime_hours_worked

#Calcualtes the employee's overtime rate.
def employee_ot_calculation():
    global employee_hourly_rate
    global employee_overtime_rate

    while employee_hourly_rate == False:
        employee_hourly_rate = raw_input("What is the employee's hourly rate?  ")

        try:
            float(employee_hourly_rate)
        except ValueError:
            print("Must use a number.")
            #print employee_hourly_rate
        else:
            employee_overtime_rate = float(employee_hourly_rate) * 1.5

#Stores travel time hours
def travel_time():
    global employee_travel_time

    while employee_travel_time == False:

        employee_travel_time = raw_input("How many hours of travel?  ")

        try:
            int(employee_travel_time)
        except ValueError:
            print("Must use a number.")
            employee_travel_time = False
        else:
            print ("Thank you.")
            #print employee_travel_time

#Stores number of working days. Not used in version .001
def number_of_days_worked():
    global days_worked

    while days_worked == False:

        days_worked = raw_input("How many days did the employee work?  ")
        days_worked = float(days_worked)
        try:
            int(days_worked)
        except ValueError:
            print("Must use a number.")
            days_worked = False
        else:
            print ("Thank you.")

#Stores earnings made by piece work from employee.
def employee_piece_earnings():
    global employee_earnings

    while employee_earnings == False:

        employee_earnings = raw_input("What did the employee earn through piece rate (format: 0.00)?  ")
        employee_earnings = float(employee_earnings)
        try:
            float(employee_earnings)
        except ValueError:
            print("Must use a number, no dollar sign.")
            employee_earnings = False
        else:
            print ("Thank you.")
            #print employee_earnings

# Calculates what the employee will earn this pay period between hours and piece work.
def overtime_piece():
    total_hours_worked = float(number_of_straight_hours_worked) + float(number_of_overtime_hours_worked)
    # print total_hours_worked

    actual_working_hours = float(total_hours_worked) - float(employee_travel_time)
    #print actual_working_hours

    piece_overtime = float(actual_working_hours) - 40
    #print piece_overtime

    overtime_rate = float(employee_earnings / actual_working_hours)
    #print overtime_rate

    earned_straight_pay = float(number_of_straight_hours_worked) * float(employee_hourly_rate)
    print "This employee earned $%.2f in straight pay: %.2f hours at $%.2f per hour" % (earned_straight_pay, number_of_straight_hours_worked, employee_hourly_rate)

    earned_hourly_overtime = (float(total_hours_worked) - float(actual_working_hours)) * float(employee_overtime_rate)
    print "This employee earned $%.2f in hourly overtime: %.2f hours at $%.2f per hour" % (earned_hourly_overtime, number_of_overtime_hours_worked, employee_overtime_rate)

    earned_piece_overtime = float(overtime_rate) * float(piece_overtime)
    print "This employee earned $%.2f in piece OT: %2f for each of working hour of the %.2f hours of overtime" % (earned_piece_overtime, overtime_rate, piece_overtime)

    total_employee_earnings = float(earned_straight_pay) + float(earned_hourly_overtime) + float(earned_piece_overtime) + float(employee_earnings)
    print "This employee earned a total of $%.2f this pay period." % total_employee_earnings

employee_ot_calculation()
straight_hours()
overtime_hours()
travel_time()
employee_piece_earnings()
overtime_piece()
4
  • 1
    Use function arguments and return values. Commented Nov 6, 2016 at 5:37
  • 4
    This question is a better fit for Code Review Stack Exchange. Commented Nov 6, 2016 at 5:41
  • Separate the logic for data entry from the calculation logic. This will make it easier to test your calculations (aka business logic). You may also see some repetition in your code that can be refactored out. First thing is definitely to replace the globals with function arguments and return values. Commented Nov 6, 2016 at 5:56
  • Thank you for your advice. Selcuk, sorry, I will keep that in mind for future posts Commented Nov 6, 2016 at 13:30

1 Answer 1

1

To avoid using global variables, what you want to do is use function arguments and return values.

Function arguments

Let's take your first function as an example. You can define a variable outside of the scope of your function and pass it as an argument between the two parenthesis. You can then manipulate your variable at your convenience inside of your function. You can pass as many arguments as you want.

number_of_straight_hours_worked = 1      # Define a variable outside of function
def straight_hours(number_of_straight_hours_worked):  #Pass as argument
    number_of_straight_hours_worked += 1 #Do whatever you want

Returning Values

The function straight_hours takes the input on how many straight hours an employee has worked. Instead of using a global variable, what you want to do is to return the value.

number_of_straight_hours_worked = ""      # Define a variable outside of function
def straight_hours(number_of_straight_hours_worked):  #Pass as argument
    number_of_straight_hours_worked = input("How many hours?")

    return number_of_straight_hours_worked

#Then retreive the value by doing
number_of_hours = straight_hours(number_of_straight_hours_worked)

As you can see, the line number_of_hours = straight_hours() calls the functions and affects the return the return value to the number_of_hours variable.

Other notes

  • I would also advise shrinking and simplifying you variable names.
  • Also, when you declare a variable like you do at the top of your code, I would advise either declare them as NONE or not do it at all. Declaring them to False which is of type boolean to then convert it to a float makes no sense to me.
  • Separete your validation code from your actual calculations. This way, you can test your calculations separately.
Sign up to request clarification or add additional context in comments.

4 Comments

The "null" value in python is None.
Thank you for your time diving into that for me. I will try these recommendations out today. As for the global Booleans, most of the tutorials I've been using seem to use True/False for while loops. Again, I don't know very much, but I will keep that in mind as I continue learning.
It is in fact verry commun to use boolean variables to control an exit condition on a while loop, for example. But those variables are usually declared near the loop itself, not at the top of the code. Also, keep me updated if you have problems understanding what I explained !
If my answer was helpful to you you can mark it as the answer you were looking for. It'd be appreciated tho! :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.