How to use multiple functions


Joined
Jan 28, 2021
Messages
1
Reaction score
0
I made a binary search function and i wanted to add a input function in order to get the array elements and the targeted numbers,i dont know how to use multiple functions and the variables break/are not detectable when i use them outside of the functions,i dont understand why, i would appreciate if someone could point out the mistakes or send a code that would fix it close to the original, thanks in advance



Screenshot (66).png
 
Ad

Advertisements

Joined
Feb 8, 2021
Messages
8
Reaction score
1
Python:
def get_input () :
    arr = []
    target = input ("pick a number to find: ")
    while len (arr) < 5 :
        x = input ("pick a number: ")
        arr.append (x)
    return target, arr

target, arr = get_input ()

def search (arr, target) :
    left = 0
    right = len (arr) - 1

    while left <= right :
        mid = (left + right) // 2
        if arr [mid] == target :
            return mid
        elif target > arr [mid] :
            left = mid + 1
        else :
            right = mid -1
    return -1

result = search (arr, target)
print (result)
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top