我应该为一个程序编写代码,该程序不断向用户询问文件名,直到它输入正确的名称 . 然后find_min_percent应该从GDP.txt文件中获取一个参数,一行(str)然后遍历该行以找到最小值并返回该值 . 到目前为止,这是我的代码
line = " "
def open_file():
''' Repeatedly prompt until a valid file name allows the file to be opened.'''
while True:
user_input = input('Enter a file name: ')
try:
file = open(user_input, 'r')
return file
break
except FileNotFoundError:
print('Error. Please try again')
open_file()
def find_min_percent(line):
'''Find the min percent change in the line; return the value and the index.'''
percent_lst = []
line = file.readline(9)
percent_lst += [line]
percent_int = [float(i) for i in percent_lst]
min_value = 10000
for percent in percent_int:
if percent < min_value:
min_value = percent
return min_value
print(open_file())
print (find_min_percent(line))
我的问题在于readline() . 它说变量文件是未定义的 . 此代码的大纲不包括“def find_min_percent(line):”部分中的文件 . 所以我不知道如何解决这个问题 . 我也不能在函数外部设置行,因为我必须在程序的后面使用相同的行变量来读取其他行 . 所以我不知道该怎么办,所以不能保留
3 回答
您在一个函数中定义的变量无法从另一个函数中访问 . 要解决这个问题,你可以这样做(将返回的值存储在“main function”变量中并将其传递给下一个函数):
顺便说一句,你使用
line
变量的方式很奇怪 . 它仅在find_min_percent
中使用,但在函数外部定义,甚至作为参数传递 . 为什么?你想要达到什么目的?(有关访问函数外部定义的变量的帖子,请参阅here)
返回的
file
变量超出了函数 Fixed code: 的范围另一种方法:
请注意,我不确定
find_min_percent
方法的正确性 . 此外,如果您手动打开文件(不使用with open
),您还需要显式关闭 .