【Class 10】 python 函数

round(a, n) 保留小数点且四舍五入

# 函数
a = 1.2353456677
## 如果想要保留小数点后两位的话,则在round 第二个参数写2
print( round(a,2) )
print( round(a,4) )

结果如下:
PS C:\Users\Administrator\Desktop\tmp> python .\Untitled-1.py
1.24
1.2353

help() 查看内置函数使用方法

>>> help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.

    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

查看python 名言

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

函数

函数的特点:

  1. 功能性
  2. 隐藏细节,方便调用
  3. 避免编写重复的代码

函数结构

def func_name(parameter_list):
	pass

1. 参数列表可以没有
2. return value,如果没有return, 默认就是 None

实例:
def add(x,y):
    result = x + y
    return result

def print_self(code):
    print(code)

print_self( add(1,3) )

函数返会多个数据

def func(a, b):
    a = a + 1
    b = b + 2
    return a,b

print( func(2, 3) )  
print( func(2, 3)[0] ) 
print( func(2, 3)[1] ) 

a = func(6,9)
print( a[0] , a[1])

输出结果:
(3, 5)
3
5
7 11

变量赋值

多个变量赋值可以简化在同一个行, a,b,c = p1,p2,p3

实例一:
a = 1
b = 2
c = 'c'

print(a, b, c)

a,b,c = 'a','b',3
print(a, b, c)

执行结果:
PS C:\Users\Administrator\Desktop\tmp> python .\Untitled-1.py
1 2 c
a b 3


实例二:
# 这样赋值结果时一个 tuple 元组
a = 1,2,3
print( type(a) )

i,j,k = a
print(i,j,k)

a = [3,5,6]
i,j,k=a
print( type(a) )
print(i,j,k)

执行结果:
<class 'tuple'>
1 2 3
<class 'list'>
3 5 6

实例三:关键字参数

关键字参数:  不用考虑形参的顺序
def add_1(x, y):
    pass

c = add_1(y=1, x=2) 

实例四: 默认参数

def add_1(x=5,y=3):
    print(x,y)

#传入全部参数,不使用默认参数
c = add_1(y=1, x=2)  
#传入一个参数,另一个使用默认参数
c = add_1(y=1)  
#一个参数都不传入,全部使用默认参数
c = add_1()  

执行结果:
PS C:\Users\Administrator\Desktop\tmp> python .\Untitled-1.py
2 1
5 1
5 3

猜你喜欢

转载自blog.csdn.net/Ciellee/article/details/87651949
今日推荐