C++猿的Python笔记03函数

  基本数据类型  
整型,长整型,浮点,复数,字符串
  变量  

无需声明或定义类型,在需要时赋值即可使用。 

  函数定义  

def 函数名(参数列表) 

变量使用无需声明或定义类型,函数也因此没有必要定义返回类型。

默认情况下返回的是None。

   函数的注意点   

1. 形参是值传递

2. 为外部变量赋值,使用global关键字

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

3. 支持默认参数

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

4. 支持关键参数。即指定实参的形参。

def func(a, b=5, c=10):
    
print 'a is', a, 'and b is', b, 'and c is', c
func(
37)
func(
25, c=24)
func(c
=50, a=100)

输出

>>> 
is 3 and b is 7 and c is 10
is 25 and b is 5 and c is 24
is 100 and b is 5 and c is 50
>>> 

5. pass表示空语句块

def someFunction():
    pass

6. 文档字符串 DocStrings

在函数定义后的第一个逻辑行若是字符串,则是这个函数的文档字符串。

即可被调用的说明语句。调用方法为 函数名.__doc__

文档字符串的惯例是:

一个多行字符串,它的首行以大写字母开始,句号结尾。

第二行是空行,

从第三行开始是详细的描述。 

def printMax(x, y):
    
'''This is DocStrings.
    
    return max number.'''
    x 
= int(x) # convert to integers, if possible
    y = int(y)
    
if x > y:
        
print x, 'is maximum'
    
else:
        
print y, 'is maximum'
printMax(
35)
print printMax.__doc__


原文地址:https://www.cnblogs.com/mumuliang/p/2131073.html