[小白系列]Python自定义函数从入门到不放弃,走过路过不要错过

  • 函数使用
  • 参数
  • 作用域
year = int(input("请输入一个年份:"))
if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
    print("{0}是闰年".format(year))
else:
    print("{0}不是闰年".format(year))

将上述代码封装成一个函数

def isleap(year):
    if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
        print("{0}是闰年".format(year))
    else:
        print("{0}不是闰年".format(year))

调用函数 isleap

isleap(2019)
2019不是闰年

判断是否为闰年时,不用再重复运行代码,只需要调用函数即可

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-S9cyJLbm-1586445387007)(attachment:landuo.jpg)]

1.函数解析

def isleap(year):
    if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
        print("{0}是闰年".format(year))
    else:
        print("{0}不是闰年".format(year))

首先看第一句

def isleap(year):
  • def:定义函数的关键字
  • isleap:自己定义的函数名
  • year:行参(形式参数),定义函数时声明,并非真正的数据

剩余部分

if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
    print("{0}是闰年".format(year))
else:
    print("{0}不是闰年".format(year))

是我们判断是否是闰年的语句

调用过程

isleap(2019)
  • isleap:函数名
  • 2019:实参(实际传入函数的数据)

2. 函数返回值 return

# 自定义加法
def my_add(x,y):
    return x + y
my_add(234,7.8)
241.8
sum = my_add(234,7.8)
print(sum)
241.8
def isleap(year):
    if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
        print("{0}是闰年".format(year))
    else:
        print("{0}不是闰年".format(year))
res = isleap(2019)
print(res)
2019不是闰年
None

None 从何而来???

思考:“2019不是闰年”是函数isleap的返回值吗?

3. 数据从何而来?–参数

3.1 可更改(mutable)与不可更改(immutable)对象

因为python 的数据类型分为两种

  • strings, tuples, 和 numbers 是不可更改的对象
  • list,dict,set 等则是可以修改的对象

mutable的类型都是引用传递,immutable都是值传递

mutbale: list就像C/C++里面的数组与链表,变量名称只是保存了数组存储的首地址,所以传递中可以直接修改引用指向的值。

immutable : 值传递只是又开辟了一块空间去保存这个值。

def my_print(x):
    x = 10
    print(x)
a = 2
my_print(a)
10
print(a)
2
def my_change_list(ls):
    ls.append('apple')
    print(ls)
ls_1 = list(range(5))
print(ls_1)
[0, 1, 2, 3, 4]
my_change_list(ls_1)
[0, 1, 2, 3, 4, 'apple']
print(ls_1)
[0, 1, 2, 3, 4, 'apple']

3,2 必备参数

必备参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样

#定义my_division()函数,观察必备参数特征
def my_division(x,y):
    return x/y
my_division(1,2)
0.5
my_division(2,1)
2.0
#调用my_division()函数---传入参数数目不一致导致报错
my_division(1)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-134-27a58249e8c5> in <module>
----> 1 my_division(1)


TypeError: my_division() missing 1 required positional argument: 'y'
#调用my_division()函数---传入参数数目不一致导致报错
my_division(1,2,3)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-136-571848a4bc12> in <module>
      1 #调用my_division()函数---传入参数数目不一致导致报错
----> 2 my_division(1,2,3)


TypeError: my_division() takes 2 positional arguments but 3 were given

3.3 关键字参数

使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值

print(my_division(1,2))
print(my_division(2,1))
0.5
2.0
print(my_division(1,2))
print(my_division(y = 2,x = 1))
0.5
0.5

3.4 默认参数

  • 创建函数时,默认参数的值需要同时给定
  • 调用函数时,默认参数的值如果没有传入,则被认为是默认值

另外要注意到函数的默认参数只可以放在函数参数列表的后面才可以

def my_division2(x, y = 3):
    return x/y
#未传入默认参数
my_division2(1)
0.3333333333333333
#传入其他参数
my_division2(1,2)
0.5
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).
 |  
 |  Methods defined here:
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __reduce__(...)
 |      Helper for pickle.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      Return a reverse iterator.
 |  
 |  count(...)
 |      rangeobject.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      rangeobject.index(value) -> integer -- return index of value.
 |      Raise ValueError if the value is not present.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  start
 |  
 |  step
 |  
 |  stop
list(range(2,10))
[2, 3, 4, 5, 6, 7, 8, 9]
list(range(3,10,2))
[3, 5, 7, 9]

3.5 不定长参数

  • 定义不定长参数时,该参数前加*或**,当传入实参多于形参时,超出部分记入不定长参数
  • 形参前面加*,接收的参数转为元组
  • 形参前面加**,接收的参数转化为字典,但参数须以赋值形式传入(传到字典里的参数必须在赋值的时候以键值对的形式才可)
def my_print2(x, *y ,**z):
    print('x:', x, type(x))
    print('y:', y, type(y))
    print('z:', z, type(z))
my_print2(1,2,3,'sd',55,'sdfdsa')
x: 1 <class 'int'>
y: (2, 3, 'sd', 55, 'sdfdsa') <class 'tuple'>
z: {} <class 'dict'>
my_print2(1,2,3,'ttt','sdaf',name = 'jack', year = 15)
x: 1 <class 'int'>
y: (2, 3, 'ttt', 'sdaf') <class 'tuple'>
z: {'name': 'jack', 'year': 15} <class 'dict'>

4. 变量作用域

  • 变量作用域规定了程序访问变量的权限
  • 局部变量:函数/循环体内定义,作用于函数内,不可被外部访问
  • 全局变量,函数/循环体外定义,或在函数/循环体内部使用“global/globals 变量名” 定义,作用于全局,函数内外均可访问
def my_division(x,y):
    result = x/y
    return result
my_division(1,2)
0.5
a = my_division(1,2)
print(a)
0.5
print(result)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-171-6459d04d738f> in <module>
----> 1 print(result)


NameError: name 'result' is not defined
def my_division(x,y):
    global result
    result = x/y
    return result
a = my_division(1,2)
print(a)
0.5
print(result)
0.5

globals:同时定义多个全局变量

发布了42 篇原创文章 · 获赞 28 · 访问量 4961

猜你喜欢

转载自blog.csdn.net/KaelCui/article/details/105423061