Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I integrate a for loop into a if statement that checks if a number exists in an array?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading