我是编程新手。我现在正在学校学习python,我遇到了一个错误,我弄清楚了。我一直收到语法错误,我不确定教师或我自己是否错字。
def main():
num_emps=int(input("How many employee records? "))
empfile=open("employee.txt","w")
for count in range(1,num_emps+1):
print("Enter data for employee#",count,sep='')
name=input("Name: ")
id_num=input("ID Number: ")
dept=input("Department: ")
empfile=write.(name+"\n")
empfile=write.(id_num+"\n")
empfile=write.(dept+"\n")
print()
empfile.close
print("Employee records written to disk")
main()
我一直在
收到错误empfile=write.(name+"\n")
或者它应该是
empfile.write(name+"\n")
感谢您的帮助
答案 0 :(得分:0)
使用empfile.write()
代替empfile=write.()
答案 1 :(得分:0)
更正和优化的版本:
def main():
# indentation was missing in your question:
num_emps = int(input("How many employee records? "))
empfile = open("employee.txt","w")
for count in range(num_emps): # range from 0 to num_emps-1
print("Enter data for employee #{}:".format(count)) # use str.format(...)
name = input("Name: ")
id_num = input("ID Number: ")
dept = input("Department: ")
empfile.write(name + "\n")
empfile.write(id_num + "\n")
empfile.write(dept + "\n")
# alternative using Python 3's print function:
# print(name, file=empfile) # line-break already included
print()
empfile.close() # to call the function, you need brackets () !
print("Employee records written to disk")
main()
此外,您的示例中并不需要编写main()
函数。您可以将代码直接放入文件中
如果你想要一个合适的main()
函数,可以使用这个构造来调用它:
if __name__ == "__main__":
main()
else:
print("You tried to import this module, but it should have been run directly!")
它用于确定脚本是直接调用还是由其他脚本导入。