如何调用多个函数

2024-04-29 01:33:24 发布

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

我有一个程序,检查社会保险号码是否有效。现在这个程序是一个大功能,它一步一步检查我输入的数字是否有几个异常。在

我想把这个大函数分成几个不同的函数,但我不知道如何,也不知道如何在一行中调用所有函数,因为它们将依赖于以前的函数结果。我要试着展示它的样子:

#i want to make this into a separate function
def numberchecker(number):
    if number > 15:
        print('bad')

#i want to make this into a separate function
    number1 = number.replace('-', '')
    number2 = number1.replace(' ', '')

#i want to make this into a separate function
    month= int(number1[2:][:2])
    if month > 13:
        print('very bad')

当一些函数相互依赖变量时,我该怎么做:/


Tags: to函数程序numbermakeiffunctionthis
2条回答

第一部分已经是一个函数,但是混淆了数字和字符串:

def check_num(num):
    return num <= 15

字符串处理函数的第二部分:

^{pr2}$

第三个变成一个布尔函数

def correct_month(str_num):
    return 1 <= str_num[2:4] <= 12

现在把它们串在一起:

if check_num(num):
    str_num = process_num(num)
    if not correct_month(str_num):
        print('very bad')
else:
    print('bad')

您要做的关键部分是在函数的末尾return一个值(在这种情况下,两个布尔值和一个字符串),以便其他函数可以继续使用它。在

如果您所做的只是验证,那么让所有函数返回True或False,例如:

def numberchecker (number):
    return number > 15

然后您可以:

^{pr2}$

相关问题 更多 >