Python课堂8--基本函数

基本函数

格式:
def 函数名(参数列表):
函数体
return

例:
(1)求绝对值

def abs(a):
    if a < 0:
        print(-a)
    else:
        print(a)
abs(-9)

(2)加减乘除:

def add(a,b):
    return (a + b)
def sub(a,b):
    return (a - b)
def mul(a,b):
    return(a * b)
def c(a,b):
    return (a / b)

(3)赋予返回值:

def add(a,b):
    c = a+b
    return c
d = add(1,2)
print(d)

return依据情况选择是否使用

(4)接下来尝试一下用函数写曾经学过的冒泡排序:

def mp(a):
    for i in range(len(a) - 1):
        for j in range(len(a) - 1 - i):
            if a[j] > a[j + 1]:
                temp = a[j]  # 定义临时变量存储a[i]
                a[j] = a[j + 1]
                a[j + 1] = temp
                del temp
b = [8,6,7,2,5,9,1]
mp(b)
print(b)

(5)然后我们用函数调用列表并显示:

def showP(person):
    for item in person:
        print(item)

f = ["hjx",30,16,100]
showP(f)

导入模块(文件)中的函数
from 后加文件名,import后加目录名

#from  库  import  模块
from com.oracle import test_tools
a = test_tools.add(1,1)
print(a)

或者

#import后加库名加模块,用点连接
import com.oracle.test_tools as t
a = t.add(2,2)
print(a)

我们在这里将test_tools命名为t,方便输入
函数命名:
as 别名

__name__的使用
如果希望我们自己可以看到的和用户界面所看到的不同,我们需要在主文件页下面加上如下代码:

#主文件运行可见
if __name__ =="__main__":
    print("主文件可见")
    # 外文件调用运行可见
else:
    print("外文件所见")

猜你喜欢

转载自blog.csdn.net/weixin_44362227/article/details/86522333