Home > Back-end >  Can I integrate a for loop into a if statement that checks if a number exists in an array?
Can I integrate a for loop into a if statement that checks if a number exists in an array?

Time:12-18

I’m writing a simple code that performs a linear search on the array numbers to see if a number entered by a user exists in it, but I keep getting syntax errors.


numbers =[1,2,3,4,5,6,7,8,9]
num= Input("enter number")
If num[for count in range(0,len(numbers))] ==numbers[for count in range(0,len(numbers))]:
    print("num is found")
else:
    print("num not found")

Have i written the IF statement correctly, or have I made a mistake

CodePudding user response:

Try this:

numbers =[1,2,3,4,5,6,7,8,9]
num= input("enter number")
if int(num) in numbers:
    print("num is found")
else:
    print("num not found")

Also if you want to make it so that it accounts for non-number responses you could use:

numbers =[1,2,3,4,5,6,7,8,9]
num= input("enter number")
try:
    if int(num) in numbers:
        print("num is found")
    else:
        print("num not found")
except:
    print("Sorry, you can only enter integers.")
  • Related