0

I'm a beginner that is currently working on a program with Python for fun and I am attempting to complete a linear search for a given list. Instead of the program returning the index of the value that is being searched for in the list, it is returning the else condition.

I created another function which is called getVal and this is so that the output of getVal will be passed into the linear search function as one of the parameters/arguments.

How would I be able to correct this so that the index number of the value being searched for in the linear search function will be the output? Any help will be greatly appreciated.

def getVal():
    userNum = int(input("Enter a number: "))
    return userNum
    if userNum != int:
       get Val

def linearSearch(searchList, getVal):
for i in range(len(searchList)):
    if i == getVal:
        return searchList.index(i)
    else:
        return "Value not found"

getVal()
linearSearch(searchList, getVal)
searchList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Eskapp
  • 3,419
  • 2
  • 22
  • 39
J.G
  • 15
  • 5
  • Your example seems a bit garbled. You're using the same names for variables and functions, which is never a good idea. The call to `getVal()` is discarding the returned value. Then it seems to be passed as an argument to `linearSearch`, where it appears to be treated as a list index. And in `getVal` itself, `get Val` is invalid syntax. – Tom Karzes Nov 09 '20 at 23:59

2 Answers2

1

Welcome to Python - this is the wrong way for searching in a list.

  1. You are comparing the value you want to find to indexes (result of range) instead of to actual values in the list.

  2. Your else clause instructs the function to return immediately after the first check (in the first iteration of the loop) fails.

To make a for loop in Python iterate over both list values and their indexes you need to use the enumerate function, like this:

def linearSearch(searchList, searchVal):
    for index, value in enumerate(searchList):
        if value == searchVal:
            return index
    
    # this line must only be reached if the loop ends without finding a match!
    return "Value not found"

Note also that while Python does allow a function to return different types of values, it is bad practice to have a function return a string in one case and a number in another.

Especially since your function can be used to search for lists containing strings, or any other type of data.

Instead, if match is not found, your function should return None. You can than check for that specific value and print the appropriate error message:

val = getVal()
res = linearSearch(searchList, val)
for is not None:
    print("{} found at index {}".format(val, res))
else:
    print("Value not found")

Finally, your getVal function will not check if the value is an integer as you expected, and instead will crush the program if something that isn't an integer is entered by the user.

Usually, testing input for integer is done with a try .. except block, but since you are new to Python, you may not have reached the topic of exceptions yet here are several suggestions on other ways of checking if you got an integer: How can I check if a string represents an int, without using try/except?

Lev M.
  • 6,088
  • 1
  • 10
  • 23
0

A couple of issues with your code:

  • if userNum != int: get Val - this will never execute because it's after a return statement, and it contains a syntax error (get Val), and you're comparing userNum which is an integer, with int which is a type
  • in the for loop "Value not found" would always be returned except if the user wanted to find the 1st element
  • the way you're calling getVal() - you're not assigning the result to any variable
  • you're passing getVal as argument to linearSearch but getVal is a function, not the value input by user

Fixed code:

In [1]: def getVal():
   ...:     userNum = int(input("Enter a number: "))
   ...:     return userNum
   ...:
   ...: def linearSearch(searchList, val):
   ...:     for i, item in enumerate(searchList):
   ...:         if item == val:
   ...:             return i
   ...:     else:
   ...:         return "Value not found"
   ...:
   ...: val = getVal()
   ...: searchList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: linearSearch(searchList, val)
   ...:
   ...:
Enter a number: 3
Out[1]: 2
Czaporka
  • 2,190
  • 3
  • 10
  • 23