2016-10-06 13 views
2

私はPythonには新しく、クラスでやっているプログラムに問題があります。 main()とcreate_fileは動作しますが、read_fileになると、インタプリタがそこに座ります。プログラムは実行されていますが、何も起こっていません。Python関数が実行されておらず、インタプリタがエラーを出さない

答えはおそらく非常に単純なものですが、私はそれを見ることはできません。助けを前にありがとう。 entryは決して中に変化しないので、あなたが関数内の無限whileループを持って

import random 

FILENAME = "randomNumbers.txt" 

def create_file(userNum): 

    #Create and open the randomNumbers.txt file 
    randomOutput = open(FILENAME, 'w') 

    #Generate random numbers and write them to the file 
    for num in range(userNum): 
     num = random.randint(1, 500) 
     randomOutput.write(str(num) + '\n') 

    #Confirm data written 
    print("Data written to file.") 

    #Close the file 
    randomOutput.close() 

def read_file(): 

    #Open the random number file 
    randomInput = open(FILENAME, 'r') 

    #Declare variables 
    entry = randomInput.readline() 
    count = 0 
    total = 0 

    #Check for eof, read in data, and add it 
    while entry != '': 
     num = int(entry) 
     total += num 
     count += 1 

    #Print the total and the number of random numbers 
    print("The total is:", total) 
    print("The number of random numbers generated and added is:", count) 

    #Close the file 
    randomInput.close() 

def main(): 

    #Get user data 
    numGenerate = int(input("Enter the number of random numbers to generate: ")) 

    #Call create_file function 
    create_file(numGenerate) 

    #Call read_file function 
    read_file() 

main() 
+1

'エントリーしばらく=「」:!'、それは永遠にループし続けるようにするには、 'ループ内entry'を変更することはありません。 – Barmar

+0

実際に実行されていますか?あなたはいくつかの機能を定義しましたが、これまでに呼びましたか? – sytech

+0

@Gator_Python最後の行を見てください: 'main()' – Barmar

答えて

6

:(。PythonとIDLE V 3.5.2)私はIDLEを使用してい

ここ

コードですループ。

ファイル内のすべての行を処理するためのPython的な方法は、このようなものです:

for entry in randomInput: 
    num = int(entry) 
    total += num 
    count += 1 
+0

コンテキストマネージャを使用してラッピングすることで、* more * pythonicにすることもできます。 –

+0

ありがとうございます!何らかの理由で私はwhileループがファイルの最後に達したときに停止すると考えました。 – NoOne

+0

私はwhileループ内にentry = randomInput.readline()を入れるのを忘れていました。うん、私は馬鹿だと感じる。 – NoOne

関連する問題