Username
Username

Reputation: 59

How to compare an input string using if statement

I am giving an input, that gets stored in the variable "inp". When I compare it in the if condition shown below, I am not getting the right output. The for loop is executed, but no output is shown. When I replace the variable by string "bin_A", I am getting the right output.

Here is the snippet of my code:

def main():
    with open("apc.json") as data_file:
      data = json.load(data_file)

    inp = raw_input("enter name") 
    print "read the input", str(inp)   
    for i in range(0,12):

      if data["work_order"][i]["bin"] == inp :  #have tried repr(inp)
          print data["work_order"][i]["bin"]
          print "gotcha", i
          print data["work_order"][i]["item"]

if __name__ == '__main__':
    main()

Note: Output of print data["work_order"][i]["bin"] is Bin_A. So, when I try to give my input as Bin_A, nothing happens

Upvotes: 0

Views: 130

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117926

Considering data was set from

data = json.load(data_file)

Then you probably need to convert the variable i from an int to a str

if data["work_order"][str(i)]["bin"] == inp

Or since you seem to use i multiple times, you could directly say

for i in map(str, range(0,12)):

Upvotes: 2

Related Questions