-1

I have tried this code of mine and it is not showing any errors also it is not showing any desired output..!!!

Code:

listx = [5, 10, 7, 4, 15, 3]
num=input("enter any number you want to search")
for i in listx :
    if num not in listx : continue
    else :    print("Element Found",i)
martineau
  • 119,623
  • 25
  • 170
  • 301

4 Answers4

1

You can simply use the in operator:

if int(num) in listx:
    print("Element Found")

The reason your code isn't working is because the elements inside the list are integers whereas the input returns a string: "5" != 5

Bhavye Mathur
  • 1,024
  • 1
  • 7
  • 25
0

The num is never in the list, therefore the loop always executes continue. If you write

num=input("enter any number you want to search")
print(type(num))

and input a number, you will see num's type is returned as 'str'. To use this input as a numeric value, simply modify to

num = int(input("enter any number you want to search"))

Also you can add a failsafe, where if the user inputs a non-numeric value, the code asks for a new input.

0

You should typecast the input to integer value

listx = [5, 10, 7, 4, 15, 3]
num=int(input("enter any number you want to search"))
if(num in listx):
    print("Element Found",i)
Ankit
  • 604
  • 6
  • 13
0

As I understood you want the index too! there are two things wrong.

  1. you used an Array List not a tuple, the code should work either way

  2. Your input comes as a string not an integer

Here's how to fix them, will not return Index of the value

tuple = (5, 10, 7, 4, 15, 3)
num = int(input("input ? ")) # the int function makes input() an integer
if num in list: print('Found!') # you don't need a for loop here

This will return the Index of the value:

for i in range(len(tuple)):
    if num not in tuple: print("Not Found"),  break # for efficiency
    if num == tuple[i]: print( 'Found at Index', i)

The difference between Array Lists and tuples are that tuples cannot change values, but an Array List can

this will produce an error

tuple[1] = "some value" 

but this won't, given that the ArrayList variable exists

ArrayList[1] = "some value"
12ksins
  • 307
  • 1
  • 12