I want the program to display a message if the user input is not in the list and continue asking for another input! What am I doing wrong?

Viewed 41

Hope everyone is doing good. I just joined this platform. So, I have just started learning python about a week or so from YouTube. This is my first program please tell me what am I doing wrong here. I want the program to display message if the user input is not in the list and continue asking for another input! Thank you.

numbers = [7,3,13,6,8,5,1,2,4,15,9,10,12,14,11]
new_list = []
while True:
    num = int(input("Enter any number from the list 'numbers': "))
    for i in numbers:
        if i < num:
            new_list.append(i)
            new_list.sort()
        elif num != i:
            print("Number doesn't exist in the list 'numbers'")
        break
    print(new_list)
2 Answers

This code would do the work:

numbers = [7,3,13,6,8,5,1,2,4,15,9,10,12,14,11]
not_in_list = True
while not_in_list:
    number = int(input("Enter any number from the list 'numbers': "))
    if number in numbers:
        not_in_list = False

the quesion you asked is not exactly what you are trying in your code. I can't undestand the idea behind creating new list. but in general you can use nested functions to write your code and continuously asking user to input data if the previous input is not what you want. remember in such cases that you are looking for number in a list that contains only numbers, you should control user input type. for instance show warning if the input is string.

numbers = [7,3,13,6,8,5,1,2,4,15,9,10,12,14,11]
def ask_number():
    num = int(input("Enter any number from the list 'numbers': "))
    check_number(num)

def check_number(num):
    if num not in numbers:
        print("Number does not exist in the list")
        ask_number()
    else:
        print(f"found {num} in list")

ask_number()
Related