The following code works correctly:
def myfunc(**kwargs):
if 'fruit' in kwargs:
print('my fruit of choice is {}'.format(kwargs['fruit']))
else:
print('No Fruit Here')
myfunc(fruit = 'apple', veggie = 'lettuce)
The following code returns an error:
def myfunc(**kwargs):
if 'fruit' in kwargs:
print(f'my fruit of choice is {fruit}')
else:
print('No Fruit Here')
myfunc(fruit = 'apple', veggie = 'lettuce)
Returns: NameError: name 'fruit' is not defined
How would I format it correctly? And also, why isn't it working the way I am trying? Is it because of **kwargs?
Thank you for any help and explaining.
Close, it should be kwargs['fruit']
because kwargs
is a dict
containing all the function's parameters
def myfunc(**kwargs):
print(kwargs)
if 'fruit' in kwargs:
print(f"my fruit of choice is {kwargs['fruit']}")
else:
print('No Fruit Here')
myfunc(fruit = 'apple', veggie = 'lettuce')
#{'fruit': 'apple', 'veggie': 'lettuce'}
#my fruit of choice is apple