Home > Software design >  printing Kwargs in for loop
printing Kwargs in for loop

Time:05-29

I have been trying to execute this code for printing out the keyword argument in for loop. I tried using both the f-string literals and .format() method, but it is giving output in 2 lines taking one value at a time. Can someone please point out what is going wrong in this code?

def myfunc(**kwargs):
    print(kwargs)
    for item in kwargs:
        print(f"my fruit of choice is : {kwargs['fruit']} and my veggie is: {kwargs['veggie']}")

myfunc(fruit='Apple',veggie='Lettuce')


CodePudding user response:

There's no need for the loop with two items, as mentioned in the comments, but here is a corrected version with a loop that will work for an arbitrary number of inputs:

def myfunc(**kwargs):
    print(kwargs)
    stringlist = []
    for i, item in enumerate(kwargs):
        if i == 0:
            string = f"my {item} of choice is: {kwargs[item]}"
        else:
            string = f"my {item} is: {kwargs[item]}"
        stringlist.append(string)
    stringlist[-1] = "and "   stringlist[-1]
    if len(kwargs) >= 3:
        print(', '.join(stringlist) '.')
    else: 
        print(' '.join(stringlist) '.')

myfunc(fruit='Apple',veggie='Lettuce')

I wouldn't use the colons, since they aren't grammatically correct, but I left them in to match your original expected output.

  • Related