python学习 (三十) python的函数

 1: 函数参数默认值

def method1(p1 = 1, p2 = 2):       // 函数有两个参数,并且都有默认值
    return p1 + p2

print(method1())          
print(method1(9))                  // 默认第一个的默认值是9
print(method1(p2=9))               // 指定第二个参数的值是9,第一个是默认值
print(method1(9,10))

 2:作用域

  如果想在函数内部使用函数外部的变量,使用global关键字

a = 10

def meth2():
    global a
    a = 56
    print(a)

meth2()
print(a)

 3:不定参数

def largest_num(*args):      // *表示多个参数,不知道有多少个
    print(max(args))

largest_num(1, 2, 3,4)
largest_num(5, 6, 7, 8)

 4: type函数

print(type(9))
print(type(99.9))
print(type("66.8"))
print(type((1, 2,3)))
print(type([1, 2,3]))
print(type({"1":2,"3":5}))

result:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'tuple'>
<class 'list'>
<class 'dict'>
原文地址:https://www.cnblogs.com/liufei1983/p/9863253.html