我刚刚开始使用Python,我一直在关注OCR GCSE计算书。 我应该复制的书中的代码是:
#valid_response="True"
while True:
answer=(input("Press A, R, F or Q: "))
if answer in("A", "a"):
write_file()
elif answer in ("R", "r"):
read_file()
elif answer in ("F", "f"):
find_rec()
elif answer in ("Q", "q"):
break
else:
print("Invalid Response")
#function to write music details to file
def write_file():
"""Write details to the file"""
#create a new file or add to an existing file
f = open("music2.txt","a")
print ("Enter Details")
ok=True
while ok==True:
serial = (input("Enter Serial "))
f.write(serial+"\n")
genre = (input("Enter Genre "))
f.write(genre+"\n")
artist = (input("Enter Artist "))
f.write(artist+"\n")
title = (input("Enter Title "))
f.write(title+"\n")
ask=(input("Another? "))
if ask in ('y', 'ye', 'yes', 'Y'):
ok=True
else:
ok=False
f.close()
我运行时得到的是错误“name write_file未定义”。
据我所知,我已经在代码中定义了它。我使用3.3.4并想知道我是否遗漏了任何明显的东西。
谢谢
答案 0 :(得分:0)
将函数移动到函数调用上方。你的主要脚本应该总是在底部。