2017-11-15 6 views
0

私はユーザが初年度と終わり年を入力できるプログラムを作成しています。プログラムはすべての年の間、間にここで私はこれまで持っているものです。Pythonで動的行を "for line in file"で印刷する

ui = input("Enter a beginning year('q' or 'Q' to quit): ") 
ui2 = input("Enter an ending year: ") 
file = open("bookListFile.txt", "r") 



def getBook(user, user2): 
    yearsBetween = int(ui2) - int(ui) 
    yearCount = 0 
    for line in file: 
     while user in line and user.isdigit() and yearCount < yearsBetween: 
      print(line) 
      yearCount += 1 



    getBook(ui, ui2) 

ここでの問題は、私はラインを印刷するとき、それは何度も同じ行を出力しています。たとえば、開始年として1985を入力し、終了年として2000を入力すると、年の代わりに同じ行が15回印刷されます。

ここで助けを得ることはできますか?可能であれば、あなたはそれをどうやって説明したでしょうか?

+0

ファイルまたはそのスニペットとプログラムの出力を投稿してください。 :)表面上では、ループと変数の宣言を少し混乱させるかもしれないように見えますが、擬似コードとテストケースの期待値を使って各行にコメントしてみてください。構文や誤った期待 –

答えて

0

whileループが巻き込まれているように見えますが、このプログラムはrange関数によってうまく機能すると思います。あなたが他の質問やコメントがあれば私に知らせてください

def get_book(user, user2): 
    year_range = range(user, user2) 
    #Instead of manually counting up through the numbers a list is automatically 
    #created through range of the numbers. Starting at user, ending at user2 and auto 
    # stepping up by 1. 
    for line in file: 
     for i in year_range: 
      #Instead of using a while loop and a manual count the for loop auto 
      #counts through the range 
      if str(i) in line: 
       print(line) 

(後世Python’s range() Function Explained用)。