2015-11-05 49 views
0

我必須從一個文本文件中提取數字,將它們放在一個列表中,並要求用戶輸入一個數字並告訴他們它是否在列表中。根據列表Python 3.x檢查用戶輸入

這是我有:

#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 

的問題是它認爲所有輸入都是無效的。我假設我搞砸了將文件轉換爲列表或使用while循環,但我不知道要修復什麼。

+0

您沒有包含數字的列表。你只有一個元素的列表,一個字符串保存文件中的所有文本。數字如何存儲在文件中?每行一個號碼? –

+0

是每個數字都在一行上。我如何將每個數字放在一個單獨的字符串中? –

回答

0

你有一個只有一個字符串的列表,整個文件的內容。

如果您的數字分別位於不同的行上,則需要使用迭代(給出單獨的行)讀取文件,並分別剝離每行。這是最好用list comprehension完成:

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

請注意,我用了一個with語句來打開該文件,這保證了當塊完成的文件將自動再次關閉。

你可能想研究規範Asking the user for input until they give a valid response關於如何編寫循環來詢問數字的問題。根據您的情況調整該帖子,並假設您仍希望將輸入處理爲字符串而不是整數:

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 
+0

是否需要定義num? 我在介紹課程,我沒有學過,所以我會離開,因爲它是。 –

+0

@BenSchutt:不,「for」循環負責將文件對象的每一行分配給你的變量。 –

+0

@BenSchutt:我已經鏈接到適合你的Python 3教程的部分,其中列出瞭解釋。 –