简体   繁体   中英

Python function not running, interpreter not giving any errors

I'm very new to Python and having a problem with a program I'm doing for a class. main() and create_file work, but when it gets to read_file, the interpreter just sits there. The program is running but nothing is happening.

The answer is probably something very simple, but I just can't see it. Thanks in advance for any help.

I'm using IDLE (Python and IDLE v. 3.5.2)

Here's the code:

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()

You have an infinite while loop in the function, since entry never changes during the loop.

The Pythonic way to process all the lines in a file is like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM