如何将此程序放入python函数中?

2024-10-02 10:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

对不起,如果我做错了什么,这是我的第一篇帖子

我想知道如何将这个程序放入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()

Tags: intxtinputifopenfile1filewrite
2条回答

只需编写如下代码,只需添加一行函数声明:

def function_name():
    #then your code here with proper indentation

#calling your function to perform defined task
function_name()

您已经声明了函数体,但对于最简单的情况(即没有参数的情况),您缺少函数声明:

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的更多信息

相关问题 更多 >

    热门问题