# Python 3.7 basic binary search

Page 1 of 1

## 3 Replies - 279 Views - Last Post: 28 September 2019 - 01:11 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=417422&amp;s=942a6583dbba710dbb4a74ae19a3215b&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 DATAfiend

Reputation: 0
• Posts: 17
• Joined: 17-February 12

# Python 3.7 basic binary search

Posted 27 September 2019 - 08:46 PM

Hi all,
I'm a noobie coder and am using a book called "Grokking Algorithms". So, the very first algo is a binary search. I'm typing in this code:
```#bin search
#
def binary_search(list, item):
low = 0
high = len(list) - 1

while low <= high:
mid = (low + high)
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None

my_list = [1, 3, 5, 7, 9]

print binary_search(my_list, 3) # => 1
print binary_search(my_list, -1) # => None

```

But I keep getting a syntax error on the "print binary_search(my_list, 3) # =>"
I'm doing this to teach myself (I have a bad teacher).

Is This A Good Question/Topic? 0

## Replies To: Python 3.7 basic binary search

### #2 modi123_1

• Suitor #2

Reputation: 15356
• Posts: 61,557
• Joined: 12-June 08

## Re: Python 3.7 basic binary search

Posted 27 September 2019 - 09:23 PM

### #3 DATAfiend

Reputation: 0
• Posts: 17
• Joined: 17-February 12

## Re: Python 3.7 basic binary search

Posted 27 September 2019 - 11:37 PM

modi123_1, on 27 September 2019 - 09:23 PM, said:

Traceback (most recent call last):
File "C:\Users\araki\AppData\Local\Programs\Python\Python37-32\binary search.py", line 19, in <module>
print (binary_search(numbers, 7)) # => 1
NameError: name 'numbers' is not defined

### #4 DK3250

• Pythonian

Reputation: 561
• Posts: 1,791
• Joined: 27-December 13

## Re: Python 3.7 basic binary search

Posted 28 September 2019 - 01:11 AM

Hm, assuming you execute python ver. 3.x, the only error I see in the code of post #1 is missing parhanteses in the print statements.

The error reported in post #3 is not from the code shown in post #1 - so, the error info is of no use; sic!

One more thing:
"list" is a python keyword - the term should not be used as a variable name.
Better make good habits from the start and avoid such potential danger fields.