0

I have to take numbers from a text file, put them in a list, and ask the user for a number and tell them whether it's in the list or not.

this is what I have:

#read numbers to list
infile = open('charge_accounts.txt','r')
lines = infile.read().strip()
list1 = [lines]
infile.close()

#ask user for #
inp = str(input('Enter an account number: '))

#determine if input is in list
#display invalid/valid
if inp in list1:
    print('valid number')
else:
    while inp not in list1:
        print('invalid entry')
        inp = input('try another number: ')
        if inp in list1:
            print('valid number')
             break

The problem is it thinks all inputs are invalid. I assume I either messed up converting the file to a list or with the while loop but I don't know what to fix.

Ben Schutt
  • 15
  • 4
  • You don't have a list with numbers. You have a list with just one element, a string holding all text in the file. How are the numbers stored in the file? One number per line? – Martijn Pieters Nov 05 '15 at 00:42
  • yes each number is on one line. how do I put each number in a separate string? – Ben Schutt Nov 05 '15 at 00:43

1 Answers1

0

You have a list with just one string in it, the contents of the whole file.

If your numbers are each on a separate line, you need to read the file using iteration (giving you separate lines) and strip each line separately. That's best done with a list comprehension:

with open('charge_accounts.txt') as infile:
    numbers = [num.strip() for num in infile]

Note that I used a with statement to open the file, this ensures that the file is automatically closed again when the block is done.

You may want to study the canonical Asking the user for input until they give a valid response question on how to write your loop to ask for numbers. Adapting that post to your situation, and assuming you still want to process the input as strings and not integers:

with open('charge_accounts.txt') as infile:
    numbers = [num.strip() for num in infile]

while True:
    account_number = input('Enter an account number: ')
    if account_number not in numbers:
        print('Invalid entry, please try again')
    else:
        break
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343