在另一个用户定义的函数中调用用户定义的函数时发生名称错误
问题描述:
我需要编写一个程序,用于打开并读取文件并包含单独的用户定义函数,用于计算文件中的行数和单词数量,例如linecount(),wordcount()等。我草拟了下面的代码,但是我一直得到一个名称错误,说“全局名称f'未定义”。 f是应该由openfile()函数返回的文件句柄。有任何建议吗?在另一个用户定义的函数中调用用户定义的函数时发生名称错误
#open and read file
def openfile():
import string
name = raw_input ("enter file name: ")
f = open (name)
# Calculates the number of paragraphs within the file
def linecount():
openfile()
lines = 0
for line in f:
lines = lines + 1
return lines
#call function that counts lines
linecount()
答
因为f
是OPENFILE局部变量
def openfile():
import string
name = raw_input ("enter file name: ")
return open (name)
# Calculates the number of paragraphs within the file
def linecount():
f = openfile()
lines = 0
for line in f:
lines = lines + 1
return lines
,甚至更短的
def file_line_count():
file_name = raw_input("enter file name: ")
with open(file_name, 'r') as f:
return sum(1 for line in f)
@ kAlmAcetA:你的回应和解决方案非常感谢。诀窍! – Sren