Finding an Input Value in a List

Viewed 426

The question from my homework is:

Write python statements that create a list which holds ten integers, and fill each slot with a different random value from 1-50. Display those values on the screen, and then get an integer from the user, search through the array, if the item exists in the list, then give the index number where it is located. If the value is not in the array, display a single message saying so.

So obviously I'm not asking the whole question on what to do it but I have tried many things and I still couldn't solve the problem that is occurring.

import random

random_list = random.sample(range(1, 50), 10)

print("Your generated random list: ", random_list)

entered_num = int(input("Value to find: "))

for a in random_list:
    if a == entered_num:
        print(a, "is in index", random_list.index(a))
    if a != entered_num:
        print(entered_num, "is not in the list.")

The output:

Your generated random list: [12, 34, 24, 47, 36, 49, 16, 5, 13, 1]
Value to find: 24
24 is not in the list.
24 is not in the list.
24 is in index 2
24 is not in the list.
24 is not in the list.
24 is not in the list.
24 is not in the list.
24 is not in the list.
24 is not in the list.
24 is not in the list.

So the problem is I don't understand why it prints out "24 is not in the list." 9 times with also one "24 is in index 2" (maybe its happening because of the random.sample generation I really don't know). I am lost here right now, I would love some help. I know this might be a stupid and an easy question for you but I'm still a beginner student in Python, although I am ready for all sort of criticism.

Note: I am using Wing Personal 7.2

2 Answers

You were almost there, the only thing is first of all the for loop is going over each element in the list and since you have the condition a != which prints every time the answer was not equal to a. and even after getting the answer you were still inside the loop and therefore you needed to break from it.

import random

random_list = random.sample(range(1, 50), 10)

print("Your generated random list: ", random_list)

entered_num = int(input("Value to find: "))

for a in random_list:
    if a == entered_num:
        print(a, "is in index", random_list.index(a))
        break 
else:
        print(entered_num, "is not in the list.")

The code is as follows:

import random

random_list = random.sample(range(1, 50), 10)

print("Your generated random list: ", random_list)

entered_num = int(input("Value to find: "))

if entered_num in random_list:
    print(entered_num, "is in the list, index:", random_list.index(entered_num))
else:
    print(entered_num, "is not in the list")

The thing being, in your case, you print everytime you make a comparison. But, you have to only print when you find it :)

Related