Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python函数未运行,解释器未给出任何错误_Python_Function - Fatal编程技术网

Python函数未运行,解释器未给出任何错误

Python函数未运行,解释器未给出任何错误,python,function,Python,Function,我对Python非常陌生,在为一个类编写程序时遇到了问题。main()和create_文件可以工作,但当它开始读取_文件时,解释器就在那里。程序正在运行,但什么也没有发生 答案可能很简单,但我就是看不出来。提前感谢您的帮助 我正在使用IDLE(Python和IDLE版本3.5.2) 代码如下: import random FILENAME = "randomNumbers.txt" def create_file(userNum): #Create and open the ran

我对Python非常陌生,在为一个类编写程序时遇到了问题。main()和create_文件可以工作,但当它开始读取_文件时,解释器就在那里。程序正在运行,但什么也没有发生

答案可能很简单,但我就是看不出来。提前感谢您的帮助

我正在使用IDLE(Python和IDLE版本3.5.2)

代码如下:

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

函数中有一个无限的
while
循环,因为
条目在循环期间从不更改

处理文件中所有行的Python方式如下:

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

输入时!='':
您从未在循环中更改
条目
,因此它将永远保持循环。您确定它确实在运行吗?你定义了一些函数,但你调用过它们吗?@Gator\u Python看最后一行:
main()
啊,谢谢@Barmar我没有向下滚动。@Barmar你说得对-我忘了在while循环中输入entry=randomInput.readline()-谢谢!我觉得有点傻,哈哈。你可以通过使用上下文管理器来包装它,让它更像python。谢谢!出于某种原因,我认为while循环在到达文件末尾时会停止。我意识到我忘了将entry=randomInput.readline()放在while循环中。啊,我觉得自己很愚蠢。