[Tutor] Fwd: Re: Passing arguments?

Alan Gauld alan.gauld at btinternet.com
Tue Oct 22 15:14:28 CEST 2013


On 22/10/13 03:23, Jenny Allar wrote:
> I ended up using the following code:

One wee improvement you could consider:

> def cal_shiprate(product_name, product_weight):
>      if product_weight < 10:
>         ship_rate = 1.5
>      elif product_weight >= 10 and product_weight < 25:
>         ship_rate = 1.45
>      else:
>          ship_rate = 1.4
>
>      total = product_weight * ship_rate
>
>      print("")
>      print(product_name, "weight in pounds              ", format
> (product_weight, '9,.2f'))
>      print ("Your total to ship", product_name, "is:      $", format
> (total, '9,.2f'))

The function is called cal_shiprate but it does more than that it prints 
it out too.
Its usually a bad idea to mix calculations and display in the same 
function so maybe you could just return the total and do the printing in 
the main function? That way you don't need to pass in the product name, 
which is not required for the calculation.

Also for the printing part the string formatting mechanism in Python 
doesn't work quite the way you have it. format() is a method of the 
string not a separate function. So your main() would end up looking 
something like:


def main ():
     name = input("Please enter the name of the product: ")
     weight = float(input("Enter weight of product in pounds: "))

     cost = cal_shiprate (weight)

     print("{} weight in pounds {:<9.2f}".format(
            product_name,product_weight))
     print("Your total to ship {} is: {:>10}{:<9.2f}".format(
            product_name, '$', cost))



Just a minor tweak.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list