1

Can you do something like this in Python?

def give_me_your_three_favorite_things_in_each_given_category(
    food=(first, second, third), 
    color=(first, second, third))
    println(f"Your favorite foods are {food.first}, {food.second} and {food.third}")
    println(f"Your favorite colors are {color.first}, {color.second} and {color.third}")

give_me_your_three_favorite_things_in_each_given_category(
    food=(first="pizza", second="pasta", third="ice cream"),
    color=(first="black", second="blue", third="green")

Expected output:
"Your favorite foods are pizza, pasta and ice cream"
"Your favorite colors are black, blue and green"

  • 1
    Use dicts? `def ...(food, ...): println(f"...{food['first']}...")`, and `give...(food={'first': 'pizza', ...})`? – deceze Aug 06 '20 at 14:31
  • Does this answer your question? [Is there a way to set a default parameter equal to another parameter value?](https://stackoverflow.com/questions/17157272/is-there-a-way-to-set-a-default-parameter-equal-to-another-parameter-value) – Unatiel Aug 06 '20 at 14:32
  • @deceze I want to have a method that specifies amount of parameters needed. Your and maor10 answers are good, but not in the case when you want user of this method to know exactly how many parameters to pass, and what those parameters mean exactly. – Stanisław Borkowski Aug 06 '20 at 14:55

1 Answers1

2

Sure- The way you would do it would be as follows:

def give_me_your_three_favorite_things_in_each_given_category(food, color):
    first_food, second_food, third_food = food
    print(f"Your favorite foods are {first_food}, {second_food}, {third_food}")
    first_color, second_color, third_color = color
    print(f"Your favorite colors are {first_color}, {second_color}, {third_color}")

You can see here that we receive tuples as paramaters, and then unpack them.

You can then call the function with

give_me_your_three_favorite_things_in_each_given_category(
food=("pizza", "pasta", "ice cream"),
color=("black", "blue", "green"))

You can also use named tuples so that you can have names for each value in the tuple:

from collections import namedtuple
Food = namedtuple("Food", ("first", "second", "third"))
Color = namedtuple("Color", ("first", "second", "third"))
give_me_your_three_favorite_things_in_each_given_category(
    food=Food(first="pizza", second="pasta", third="ice cream"),
    color=Color(first="black", second="blue", third="green")
)
maor10
  • 1,645
  • 18
  • 28