0

Just started with Python and trying to get this to work. I need to get user input on a number between 1 through 50 and then iterate through a list of numbers and find a match. My code is not working and I am not sure what I am doing wrong. Can you help me?

>>> numbers = [1,3,5,7,9,11,15,18,21,23,34,35,38,41,43,47,49]
>>> n=0
>>> while True:
    print("Type q to quit")
    answer = input("Guess a number between 1 a 50: ")
    if answer == "q":
        break
    if answer in numbers:
        print("Number " + answer + " was found! Congrats!")
        break
    elif answer not in numbers:
        print("Number " + answer + " was not found! Try again!")
        continue
    n += 1
  • 1
    What does "My code is not working" mean? What happens when you run your code? What do you want it to do instead? Have you done any debugging? If so, what did you learn from the debugging that might cause the problem? If you haven't done any debugging, read [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for some tips to get you started. – Code-Apprentice Dec 30 '20 at 22:12
  • 2
    `answer` is a string, you need to convert it to an `int` first – UnholySheep Dec 30 '20 at 22:12
  • 1
    https://docs.python.org/3/library/functions.html#input - "The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.".. – rasjani Dec 30 '20 at 22:13
  • 1
    You don't need an `elif`, just an `else`. If `answer in numbers` is false, then `answer not in numbers` is necessarily true. – chepner Dec 30 '20 at 22:23

2 Answers2

1

answer is a string but numbers contains ints. Parse the answer to an int:

numbers = [1,3,5,7,9,11,15,18,21,23,34,35,38,41,43,47,49]
# take this out of the loop since you don't need to print it every time
print("Type q to quit")
while True:
    answer = input("Guess a number between 1 and 50: ")
    if answer == "q":
        break
    # parse to int
    try:
        answer = int(answer)
    except ValueError:
        print("Please enter a valid number.")
        continue
    if answer in numbers:
        # use f-string to serialize number back into a string
        print(f"Number {answer} was found! Congrats!")
        break
    # don't need elif since answer must not be in numbers
    else:
        print(f"Number {answer} was not found! Try again!")
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

answer is a string, while the items in numbers are ints. If you want to use the in operator, you'll have to convert them to the same type. E.g.:

if int(answer) in numbers:
Mureinik
  • 297,002
  • 52
  • 306
  • 350