python3 | 函数

1、内置函数

Python内置了很多有用的函数,可以直接调用这些内置函数。

# 我是大青呐学习python笔记
# abs():函数返回数字的绝对值
a = abs(-20.3)
print(a)
# int():转换为整型
b = int(10.78)
print(b)
# sorted():对序列化类型数据正向排序,返回一个新的对象,默认是升序,降序: reverse=True
c = sorted([5,3,8,2,6,0,4])
print(c)
# input():提示用户输入,接受标准输入,返回为 string 类型。
d = input("please input:")
print(d)
# iter() 函数用来生成迭代器。
list = [1, 2, 3, 4]
for i in iter(list):
    print(i)
# len():返回对象(字符、列表、元组等)长度。
e = len(list)
print(e)

运行结果

20.3
10
[0, 2, 3, 4, 5, 6, 8]
please input:haha
haha
1
2
3
4
4

3、定义函数

定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号在缩进块中编写函数体,函数的返回值用return语句返回。

def greet():
    print("Hello!")

greet()

def  sum(a,b):
    c = a + b
    return c
s = sum(2,3) #传递实参
print(s)

运行结果

Hello!
5

3、函数的结合使用

可将函数同其他的结构结合起来,列如下面结合get_name()函数和while循环来问候用户。

提示用户输入自己的姓名,并提示如何退出。

def  get_name(first_name,last_name):
    full_name = first_name + ' '+last_name
    return  full_name.title()
while True:
    print("\nPlease input your name:")
    print("(enter 'q' at any time to quit)")
    f_name = input("First name:")
    if f_name == 'q':
        break
    l_name = input("Last name:")
    if l_name =='q':
        break
    name = get_name(f_name,l_name)
    print("\nHello,"+name+" !")

运行结果

Please input your name:
(enter 'q' at any time to quit)
First name:zhang
Last name:zina

Hello,Zhang Zina !

Please input your name:
(enter 'q' at any time to quit)
First name:wang
Last name:qitao

Hello,Wang Qitao !

Please input your name:
(enter 'q' at any time to quit)
First name:q

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_42646885/article/details/88871406