zoukankan      html  css  js  c++  java
  • python学习笔记之函数(方法)

    def func(x):
        print 'x is', x
        x = 2
        print 'Changed local x to', x
    
    x = 50
    func(x)
    print 'x is still', x

    结果:

    x is 50
    Changed local x to 2
    x is still 50

    在函数内改变全局变量的值(global)

    def func():
        global x
    
        print 'x is', x
        x = 2
        print 'Changed local x to', x
    
    x = 50
    func()
    print 'Value of x is', x

    结果:

    x is 50
    Changed global x to 2
    Value of x is 2

    默认参数

    def say(message, times = 1):
        print message * times
    
    say('Hello')
    say('World', 5)

    结果:

    Hello
    WorldWorldWorldWorldWorld

    关键参数

    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

    函数的return

    def maximum(x, y):
        if x > y:
            return x
        else:
            return y
    
    print maximum(2, 3)

    结果:3

    空语句块pass

    def someFunction():
        pass

    DocStrings

    读取函数的doc注释信息,DocStrings也适用于模块

    文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。

    def printMax(x, y):
        '''Descript:
            this is printMax function descript
        end.'''
        x = int(x) # convert to integers, if possible
        y = int(y)
    
        if x > y:
            print x, 'is maximum'
        else:
            print y, 'is maximum'
    
    printMax(3, 5)
    print printMax.__doc__
    print '---'
    help(printMax)

    结果

    5 is maximum
    Descript:
            this is printMax function descript
        end.
    ---
    Help on function printMax in module __main__:
    
    printMax(x, y)
        Descript:
            this is printMax function descript
        end.
  • 相关阅读:
    react-native 之ScrollView的使用
    gitHub 克隆项目慢
    react native 给View添加点击事件
    React Native View属性onLayout
    react native 样式与布局
    react native 对日期的处理
    react native 顶部菜单栏效果的实现
    iOS self.navigationController 推出界面怎么一次性回到指定第一个
    Java
    2021-5-13讲课内容hibernate主键id映射_XML方式
  • 原文地址:https://www.cnblogs.com/yangzhilong/p/3772867.html
Copyright © 2011-2022 走看看