[英]Nameerror when calling a user-defined function in another user-defined function
我需要編寫一個程序來打開和讀取文件,並包含單獨的用戶定義函數來計算文件中的行數和單詞數,例如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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.