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?
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
.
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?
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
.