0

im just getting into python for my discrete structures and algorithms class > and for some reason, im getting an error with my syntax and I don't understand why can you assist this is the error:

line 10

i = i + 1

IndentationError: unindent does not match any outer indentation level also for some reason my code isn't printing

#linear search algorithm
 def search(list1, n):
    i = 0

    while i < len(list1):
         if list1[i] == n:
            print("found now")
            return True
        i = i + 1

    return False


list1 = [1,5,9,3,4,6]
n = 6

if search(list1, n):
    print("found")
else:
    print("not found")
  • 3
    As the error message says, it's because your indentation is incorrect. The `if` statement and `i = i + 1` aren't even with each other. –  Apr 12 '19 at 00:14
  • Three spaces from the `def` to the `i = 0`, five from the `while` to the `if`, four from the `while` to the `i = i + 1`. You should pick one scheme (preferably four spaces as per PEP8, https://www.python.org/dev/peps/pep-0008/) and stick with it. – paxdiablo Apr 12 '19 at 00:22

2 Answers2

0

As others have mentioned in your comments, your indentation is wonky. Pythonic code prefers 4 spaces for every indented/unindented line.

To linear search for an element in a list data structure, you can use the in keyword. Here is your code functionally, but with less lines:

list1 = [1,5,9,3,4,6]
n = 6

if n in list1:
    print("found") # Indent 4 spaces
else: # Unindent 4 spaces
    print("not found") # Indent 4 spaces

Now for your code:

 def search(list1, n): # Careful! You have an extra space here.
    i = 0 # Indent 3 spaces

    while i < len(list1):
         if list1[i] == n: # Indent 5 spaces
            print("found now") # Indent 3 spaces
            return True
        i = i + 1 # Unindent 4 spaces

    return False # Unindent 4 spaces

So remove the extra space at the start, and fix it to 4 spaces each time.

Note: The in keyword can be used on other iterables (tuples, dictionaries, sets, etc...) as well, or objects with __contains__ in the class.

Since this is a class, they probably just want you to familiarize yourself with linear search by using an index variable (e.g. for i in ....) as you've done, but the python already does this for you in the background with the in keyword.

jsonV
  • 1,650
  • 2
  • 9
  • 23
0

Python was a "tab" ( indent) sensitive programming languages , make sure you remove\add tab\space when you use function\ if \ while loop etc

you are advise to use IDE tools to detect syntax error ( in my case i am using Visual studio 2017 ) ,

IDE show which line you have make mistake

your code shall look like something as below where tab\space are align

enter image description here

HO LI Pin
  • 1,441
  • 13
  • 13