0

Hi new to python and programming in general I'm trying to find an element in an array based on user input here's what i've done

a =[31,41,59,26,41,58]
input = input("Enter number : ")
for i in range(1,len(a),1) :
    if input == a[i] :
       print(i)

problem is that it doesn't print out anything. what am I doing wrong here?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
YBb
  • 11
  • 4

4 Answers4

1

input returns a string. To make them integers wrap them in int.

inp=int(input('enter :'))
for i in range(0,len(a)-1): 
    if inp==a[i]:
        print(i)

Indices in list start from 0 to len(list)-1.

Instead of using range(0,len(a)-1) it's preferred to use enumerate.

for idx,val in enumerate(a):
    if inp==val:
        print(idx)

To check if a inp is in a you can this.

>>> inp in a
True #if it exists or else False

You can use try-except also.

try:
    print(a.index(inp))
except ValueError:
    print('Element not Found')
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
0

input returns a string; a contains integers.

Your loop starts at 1, so it will never test against a[0] (in this case, 31).

And you shouldn't re-define the name input.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Please don't declare a variable input is not a good practise and Space is very important in Python

a =[31,41,59,26,41,58]
b = input("Enter number : ")
for i in range(1,len(a),1):
    if int(b) == a[i] :
        print(i)

I think you want to check a value from your list so your input need to be a Int. But input takes it as String. That's you need to convert it into int.

Shantanu Nath
  • 363
  • 3
  • 13
0

input is providing you a str but you are comparing a list of ints. That and your loop starts at 1 but your index starts at 0

jcirni
  • 57
  • 4