对不起,如果我做错了什么,这是我的第一篇文章。
我想知道如何将该程序放入def函数中。
提前谢谢。
file = open("Moradores.txt", "a+")
file1 = open("Moradores.txt", "r", encoding="utf-8")
lerFile = file1.read()
mName = input("Nome: ")
if mName in lerFile:
while True:
print("O nome ja existe, tente outro")
mName = input("Nome: ")
if mName not in lerFile:
break
mEmail = input("Email: ")
mPass = input("Senha: ")
file.write(mName + "|")
file.write(mEmail + "|")
file.write(mPass + "|")
file.write("\n")
print("Continue registering?")
print("1 - YES || 2 - NO")
choice = input()
if choice == '2':
break
elif choice != '1':
print("Invalid option")
print("Continue registering?")
print("1 - YES || 2 - NO")
choice = input()
file.close()
答案 0 :(得分:2)
您已经声明了函数的主体,只是在最简单的情况下(即没有参数的情况)缺少了函数声明:
def do_something():
while True:
file = open("Moradores.txt", "a+")
file1 = open("Moradores.txt", "r", encoding="utf-8")
lerFile = file1.read()
mName = input("Nome: ")
if mName in lerFile:
while True:
print("O nome ja existe, tente outro")
mName = input("Nome: ")
if mName not in lerFile:
break
mEmail = input("Email: ")
mPass = input("Senha: ")
file.write(mName + "|")
file.write(mEmail + "|")
file.write(mPass + "|")
file.write("\n")
print("Continue registering?")
print("1 - YES || 2 - NO")
choice = input()
if choice == '2':
break
elif choice != '1':
print("Invalid option")
print("Continue registering?")
print("1 - YES || 2 - NO")
choice = input()
file.close()
如果需要其他参数,请按以下方式在函数声明中声明它:
def do_something(arg1, arg2, ...):
最适合您代码的声明是
def do_something():
(当然,您可以更改函数的名称)
您可以阅读有关功能here的更多信息。
答案 1 :(得分:1)
只需像下面那样编写代码,只需添加一个函数声明行:
def function_name():
#then your code here with proper indentation
#calling your function to perform defined task
function_name()