您的位置:首页 > 编程语言 > Python开发

Python学习之函数

2015-08-02 20:46 597 查看
# coding=utf-8

import math

x = 1

print math.sqrt(x)

# callable函数可以判断函数是否可以调用

y = math.sqrt

print callable(x)

print callable(y)

def hello(name):

return 'Hello, ' + name + '!'

print hello('world')

print hello('Gumby')

def fibs(num):

result = [0, 1]

for i in range(num - 2):

result.append(result[-2] + result[-1])

return result

print(fibs(10))

# 记录函数

def square(x):

'Calculates the square of the number x.'

return x * x

print square.__doc__

# 参数改变

def try_to_change(n):

n = 'Mr. Gumby'

name = 'Mrs.Entity'

try_to_change(name)

print name

def change(n):

n[0] = 'Mr.Gumby'

names = ['Mrs.ENtity', 'Mrs. Thing']

change(names)

print names

# 关键字参数和默认值

def hello_1(greeting, name):

print '%s, %s!' % (greeting, name)

print hello_1(greeting='Hello', name='World')

print hello_1(name='World', greeting='Hello')

def hello_2(greeting='Hello', name='World'):

print '%s, %s!' % (greeting, name)

print hello_2()

print hello_2('Greetings')

# 收集参数

def print_params(*params):

print params

# 结果为元组打出来

print_params('Test')

print_params(1, 2, 3)

def print_params_2(title, *params):

print title

print params

print_params_2('Params:', 1, 2, 3)

# 返回的是字典

def print_param_3(**params):

print params

print_param_3(x=1, y=2, z=3)

def print_param_4(x, y, z=3, *pospar, **keypar):

print x, y, z

print pospar

print keypar

print print_param_4(1, 2, 3, 5, 6, 7, foo=1, bar=2)

# 反转过程

def add(x, y):

return x + y

param = (1, 2)

print add(*param)

param = {'name': 'zhangsang', 'age': '100'}

hello_2(*param)

# 作用域

def foo(): x = 42

x = 1

foo()

print x

# 递归

def factorial(n):

if (n == 1):

return 1

else:

return n * factorial(n - 1)

print factorial(4)

def search(sequence, number, min, max):

middle = (min + max) / 2

num = int(sequence[middle])

if (num == number):

return middle

elif (num > number):

return search(sequence, number, min, middle - 1),

else:

return search(sequence, number, middle - 1, max),

print search('12345678', 4, 0, 7)

# Lambda函数,匿名函数

g = lambda x: x ** 2

print g(4)

a = lambda i, x: i ** 2 / x - i

print a(2, 6)

print map(lambda x: x ** 2, [i for i in range(10)])

# 等价于

a = range(10)

print map(lambda x: x ** 2, a)

# Pickle序列化

import pickle

account_info = {

'11111111': ['11112222', 1500, 19000],

'22222222': ['11112222', 1500, 19000]

}

# 二进制方式打开

f = file('account.dat', 'wb')

pickle.dump(account_info, f)

f.close()

f = file('account.dat')

name_list = pickle.load(f)

print name_list

# 正则表达式

import re

# 将正则表达式编译成Pattern对象

pattern = re.compile(r'Hello')

# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None

match = pattern.match('Hello,world')

print pattern.findall('Hello,world,Hello')

if match:

print match.group()

m = re.match(r'Hello', "Hello,world")

print m.group()

# 匹配一个数字

p = re.compile('\d')

print p.findall('dafkd3,4,k,kkkkkkkkkkkkk6')

# 匹配非数字

p = re.compile('\D')

print p.findall('dafkd3,4,k,kkkkkkkkkkkkk6')

# 匹配任何空白字符

p = re.compile('\s')

print p.findall('dafkd3,4,k,kkd kkkk kkkkkkk6')

# 匹配字母加数字

p = re.compile('\w')

print p.findall('dafkd3,4,k,kkd kkkk kkkkkkk6')

# 匹配非字母加数字

p = re.compile('\W')

print p.findall('dafkd3,4,k,kkd kkkk kkkkkkk6')

# 匹配一个或多个

p = re.compile('\d+')

# 按照能匹配的字串将原字符分割后返回列表

print p.split('abcdef23234fdsafdasw55dd5')

print p.findall('abcdef23234fdsafdasw55dd5')

# 替换

print re.sub('[abc]', 'o', 'Mark')

print re.sub('\d', 'dd', 'Mark 4 Lily')

# 模块

import sys

print sys.path

print sys.platform

print sys.maxint

print sys.version

import os

print os.path

print os.curdir

print os.defpath

print os.system('uname')

# print os.system('dir')

# os.mkdir('myDir')

import commands

print commands.getstatusoutput('dir')

print os.lstat('box.py')

# 生成迭代器

iter([x for x in range(10)])

# 或

(x for x in range(10))

输出:

"D:\Program Files\Python\python.exe" G:/HelloPython/list/function.py

1.0

False

True

Hello, world!

Hello, Gumby!

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Calculates the square of the number x.

Mrs.Entity

['Mr.Gumby', 'Mrs. Thing']

Hello, World!

None

Hello, World!

None

Hello, World!

None

Greetings, World!

None

('Test',)

(1, 2, 3)

Params:

(1, 2, 3)

{'y': 2, 'x': 1, 'z': 3}

1 2 3

(5, 6, 7)

{'foo': 1, 'bar': 2}

None

3

age, name!

1

24

3

16

-2

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

{'11111111': ['11112222', 1500, 19000], '22222222': ['11112222', 1500, 19000]}

['Hello', 'Hello']

Hello

Hello

['3', '4', '6']

['d', 'a', 'f', 'k', 'd', ',', ',', 'k', ',', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k']

[' ', ' ', ' ', ' ']

['d', 'a', 'f', 'k', 'd', '3', '4', 'k', 'k', 'k', 'd', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', '6']

[',', ',', ',', ' ', ' ', ' ', ' ']

['abcdef', 'fdsafdasw', 'dd', '']

['23234', '55', '5']

Mork

Mark dd Lily

['G:\\HelloPython\\list', 'G:\\HelloPython', 'C:\\Windows\\system32\\python27.zip', 'D:\\Program Files\\Python\\DLLs', 'D:\\Program Files\\Python\\lib', 'D:\\Program Files\\Python\\lib\\plat-win', 'D:\\Program Files\\Python\\lib\\lib-tk', 'D:\\Program Files\\Python',
'D:\\Program Files\\Python\\lib\\site-packages']

win32

2147483647

2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)]

<module 'ntpath' from 'D:\Program Files\Python\lib\ntpath.pyc'>

.

.;C:\bin

MINGW32_NT-6.1

0

(1, "'{' \xb2\xbb\xca\xc7\xc4\xda\xb2\xbf\xbb\xf2\xcd\xe2\xb2\xbf\xc3\xfc\xc1\xee\xa3\xac\xd2\xb2\xb2\xbb\xca\xc7\xbf\xc9\xd4\xcb\xd0\xd0\xb5\xc4\xb3\xcc\xd0\xf2\n\xbb\xf2\xc5\xfa\xb4\xa6\xc0\xed\xce\xc4\xbc\xfe\xa1\xa3")

nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid=0, st_size=477L, st_atime=1438422558L, st_mtime=1438422558L, st_ctime=1438422219L)

Process finished with exit code 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: