Home > Mobile >  When I try to run this code, it is giving the NameError, saying : name 'x' is not defined,
When I try to run this code, it is giving the NameError, saying : name 'x' is not defined,

Time:01-07

When I try to run this code, it is giving the NameError, saying: name 'x' is not defined, It is happening only when I implicitly try to run all cases

    dict={}
    for queryname in dict.keys():
        if queryname in dict.keys()
        x=dict.get(queryname)
    formatted_float = "{:.2f}".format(sum(x)/3)
    print(formatted_float)

CodePudding user response:

If d is empty, then the for loop will never run, because it has nothing to iterate on. The body of the loop will never be executed, and that includes the assignment of x. You can either add some keys to d, or assign x to some value before the loop.

# Adding keys
d = {0:1, 2:3} #Don't use dict as a variable name, that collides with the python keyword.
for queryname in d.keys():
        if queryname in d.keys()
        x = d.get(queryname)
    formatted_float = "{:.2f}".format(sum(x)/3)
    print(formatted_float)
#Assigning a value to x
d = {}
x=0
for queryname in d.keys():
        if queryname in d.keys()
        x = d.get(queryname)
    formatted_float = "{:.2f}".format(sum(x)/3)
    print(formatted_float)

CodePudding user response:

I know to give dict some value, this is a code in hackerrank, in order to run all test cases, I just gave dict as a random input.

  •  Tags:  
  • Related