gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:08:26 25 4
gpt4 key购买 nike

我是 Python 的新手,我在类里面编写的程序有问题。 main() 和 create_file 工作,但是当它到达 read_file 时,解释器只是坐在那里。程序正在运行,但没有任何反应。

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

我正在使用 IDLE(Python 和 IDLE v. 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 循环,因为 entry 在循环期间永远不会改变。

处理文件中所有行的 Pythonic 方式是这样的:

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

关于Python 函数未运行,解释器未给出任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39906388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com