Keyword argument (kwargs) function error in Python

Question:

Following is the code:

def my_funct(**kwarg):
    print(kwarg[fn]*kwarg[sn])
print('enter 2 numbers to get product of')
a=input()
print('enter second number')
b=input()
my_funct(fn=a,sn=b)

The output is error saying ‘fn is not defined’. What is the solution?

Asked By: Abubakker Hashmi

||

Answers:

Kwargs is a dictionary where the variable name is the key and has type str. You are trying to find the value to the key which is saved in the variable fn but this variable hasn’t been defined. Instead what you want is the value corresponding to the key 'fn', so you do

print(kwarg['fn'] * kwarg['sn'])

Edit: Because your corresponding values come from the input() function, you should make sure they are actually numbers and not strings. So when you do a=input() you should change that to a=float(input()). Same for b.

Answered By: yagod
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.