Home > Net >  How can I use two lists as arguments in a function?
How can I use two lists as arguments in a function?

Time:01-29

I am learning python and I came up with this exercise, but I can't find a way that this can work. The idea is to loop through two lists and use each value as an argument to the function.

def make_tshirt(size, text='I love Python!'):
    v = []
    if len(text) <= 20:
        v = ['S', 'M', 'L']
    elif len(text) <= 30:
        v = ['M', 'L']
    elif len(text) <= 50:
        v = ['L']
    else:
        v = []

    if text == '':
        text = 'I love Python!'

    if size in v:
        print(f"You ordered a {size} tshirt with the text '{text}'.")
    else:
        print("The size you want don't have enough space to your text.")

sizes = ['m', 's', 'l', 's']
texts = ['I like Python', 'Am I a robot?', 'Weird Year', 'God, Our savior']

make_tshirt([x.upper() for x in sizes], [y for y in texts])

I need this code to print the result of the funciton four times, as shown below:

You ordered a M tshirt with the text 'I like Python'.    
You ordered a S tshirt with the text 'Am I a robot?'.    
You ordered a L tshirt with the text 'Weird Year'.    
You ordered a S tshirt with the text 'God, Our savior'.

CodePudding user response:

In Python, you can use zip() function which takes two or more iterables as arguments of function and returns an iterator of the tuples. The nth tuple will contain the nth element from each of input iterables. Here is the demonstration:

def make_tshirt(size, text='I love Python!'):
v = []
if len(text) <= 20:
    v = ['S', 'M', 'L']
elif len(text) <= 30:
    v = ['M', 'L']
elif len(text) <= 50:
    v = ['L']
else:
    v = []

if text == '':
    text = 'I love Python!'

if size in v:
    print(f"You ordered a {size} tshirt with the text '{text}'.")
else:
    print("The size you want don't have enough space to your text.")

sizes = ['m', 's', 'l', 's']
texts = ['I like Python', 'Am I a robot?', 'Weird Year', 'God, Our savior']

for size, text in zip([x.upper() for x in sizes], texts):
    make_tshirt(size, text)

CodePudding user response:

Use the zip built-in function to get each order's size and text.

for pair in zip(sizes, texts):
    make_tshirt(pair[0], pair[1])
  • Related