Can someone please look at my code and see if I'm writing it efficiently using parameters and return values.

Thank you for your support

PAY_RATE = 12.75

#This program ask the user for: hours worked, then calculates gross pay.

def get_hours():
    hours = input("How many hours did you work?: ")
    return hours
 
def calc_gross_pay(hours):
    gp = float(hours) * PAY_RATE
    print "Gross Pay $%0.2f" %  gp

def main():
    hours = get_hours()
    calc_gross_pay(hours)
    
main()

Recommended Answers

All 4 Replies

Member Avatar for leegeorg07

yep that works, i tested it with this loop:

PAY_RATE = 12.75

#This program ask the user for: hours worked, then calculates gross pay.
a = 1
b = []
def get_hours():
    hours = a
    return hours
 
def calc_gross_pay(hours):
    gp = float(hours) * PAY_RATE
    print "Gross Pay $%0.2f" %  gp
	
def main():
	hours = get_hours()
	calc_gross_pay(hours)
	

while a <=100000000000000000000000:
	main()
	a+=1

The style is good too. In general, functions should do one thing and do it well. Yours pass that criterion.

Although ... I don't usually have a "main()" for the simple reason that I like to examine variables if the program crashes, and stuffing the main code into main() makes that more difficult.

Good work!
Jeff

Yet on that note, if you want to import something it is usually a lot better to have a main() function as then you can go:

if __name__ == '__main__':
    main()

And i find that a lot more readable then

if __name__ == '__main__':
    #every part of main would go here

I guess its just general preference, what works for you?

Yes, I actually do the latter.

ACTUALLY, what I often do is this:

class MyClass(object):
   ....
   @staticmethod
   def test():
       ## Unit testing goes here

if __name__ == "__main__":
   MyClass.test()

and then the test method is responsible for spitting out diagnostics. But in the absence of full unit testing, I put the main code after the if __name__ clause.

I should note also that my main code is almost always short, because the heavy lifting is done by functions and class methods. The only reason, then, to not have a main() function is so that I can have one or more named instances of objects whose state can be examined if needed.

Jeff

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.