Python Forum
return string from function with one argument
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
return string from function with one argument
#2
The solution is the same solution I would use for solving this with C, create an association between the shipping cost function and the shipping cost name. In Python I might use a dictionary.
def ground_shipping_cost(weight):
  cost = weight * 4.00
  return cost
 
def drone_shipping_cost(weight):
  cost = weight * 4.50
  return cost

def premium_ground_cost(weight):
    return 125

shipping_options = {
    'Ground': ground_shipping_cost,
    'Drone': drone_shipping_cost,
    'Premium Ground' : premium_ground_cost
    }

def method_is_cheapest(weight):
    option = None
    min_cost = 0
    for name in shipping_options:
        cost = shipping_options[name](weight)
        if cost < min_cost or option is None:
            min_cost = cost
            option = name
    return option

weight = float(input('Enter package weight: '))
option = method_is_cheapest(weight)
cost = shipping_options[option](weight)
print(f'Shipping {option} is the cheapest at ${cost:.2f}')
Reply


Messages In This Thread
RE: return string from function with one argument - by deanhystad - May-28-2020, 11:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  mutable argument in function definition akbarza 1 494 Dec-15-2023, 02:00 PM
Last Post: deanhystad
  nested function return MHGhonaim 2 624 Oct-02-2023, 09:21 AM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 2,315 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  function return boolean based on GPIO pin reading caslor 2 1,193 Feb-04-2023, 12:30 PM
Last Post: caslor
Information How to take url in telegram bot user input and put it as an argument in a function? askfriends 0 1,109 Dec-25-2022, 03:00 PM
Last Post: askfriends
  i want to use type= as a function/method keyword argument Skaperen 9 1,909 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 4,893 Jul-01-2022, 01:23 PM
Last Post: deanhystad
  Convert a string to a function mikepy 8 2,558 May-13-2022, 07:28 PM
Last Post: mikepy
  return vs. print in nested function example Mark17 4 1,757 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  Regex - Pass Flags as a function argument? muzikman 6 3,622 Sep-06-2021, 03:43 PM
Last Post: muzikman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020