Python基础(三)

局部变量

x = 50


def func(x):
    print('x is', x)
    x = 2
    print('change local x to', x)
    

func(x)
print('x is still', x)

输出:

x is 50
change local x to 2

x is still 50


global语句

x = 50


def func():
    global x
    print('x is', x)
    x = 2
    print('change global x to', x)


func()
print('value of x is', x)

输出:

x is 50
change global x to 2
value of x is 2


默认参数

只有位于参数列表尾部的参数才能被赋予默认参数值

def say(message, times=1):
    print(message * times)


say('Hello')
say('Hello', 5)

输出:

Hello

HelloHelloHelloHelloHello


关键字参数

使用命名(关键字)而非位置来指定函数的参数。

def func(a, b=5, c=10):
    print('a is', a, 'and b is', b, 'and c is', c)


func(3, 7)
func(25, c=24)
func(c=50, a=100)

输出:

a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24

a is 100 and b is 5 and c is 50


可变参数

*param,从此处开始直至结束的所有关键字参数都将被收集并汇集成一个名为param的 元祖(Tuple).

**param,从此处开始直至结束的所有关键字参数都将被收集并汇集成一个名为param的字典(Dictionary)。

def total(a=5, *numbers, **phonebook):
    print('a', a)

    # 遍历元祖中所有项目
    for single_item in numbers:
        print('single_item', single_item)

    # 遍历字典中的所有项目
    for first_part, second_part in phonebook.items():
        print(first_part, second_part)


print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))

输出:

a 10
single_item 1
single_item 2
single_item 3
Jack 1123
John 2231
Inge 1560

None


DocStrings文档字符串

文档字符串也适用于模块与类

约定的是一串多行字符串,第一行以某一大写字母开始,以句号结束。

第二行为空行,第三行是任何详细的解释说明。

通过函数的__doc__属性来获取文档字符串属性

def print_max(x, y):
    """Prints the maximum of two numbers.打印两个数值中的最大值。

    The two value must be integers.这两个数都应该式整数"""
    x = int(x)
    y = int(y)

    if x > y:
        print(x, 'is maximum')
    else:
        print(y, 'is maxinum')


print_max(3, 5)
print(print_max.__doc__)

输出:

5 is maxinum
Prints the maximum of two numbers.打印两个数值中的最大值。


    The two value must be integers.这两个数都应该式整数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值