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

Python练习 - 廖雪峰教程

2016-04-22 18:07 429 查看
#coding:utf-8
# print absolute value of an integer:
a=90
if a>=0:
print a
else:
print -a

print 'I\'m \"OK\"!'
print 'I\'m learning\nPython.'
print '''line1
line2
line3'''
print 3>2
print 3>5
print 3>2 and 3>5

a = 'ABC'
b = a
a = 'XYZ'
print b
print a
print ord('A')
print chr(85)
print '中文'
print 'Hello,%s' %'World'
print 'Hi,%s,you have $%d' %('Lcjun',1000000)
print '%d-%02d' %(3,1)
print '%.2f' %3.141592654
print 'growth rate:%d %%' %7
classmates = ['Michael', 'Bob', 'Tracy']
print classmates
print len(classmates)
print classmates[0]
print classmates[1]
print classmates[2]
print classmates[-1]
print classmates[-2]
print classmates[-3]
classmates.append('Adam')
print classmates
classmates.insert(1,'Jack')
print classmates
classmates.pop()
print classmates
classmates.pop(0)
print classmates
s = ['python', 'java', ['asp', 'php'], 'scheme']
print s
print len(s)
print s[2]
print s[2][0]
#以下是元祖tuple结构了,内容不允许修改
classmates = ('Michael', 'Bob', 'Tracy')
print classmates
print classmates[0]
print classmates[1]
print classmates[2]
#所以,只有1个元素的tuple定义时必须加一个逗号,,来消除歧
t = (1,)
print t
t = ('a', 'b', ['A', 'B'])
print t
print t[2][0]
print t[2][1]
#表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素
t[2][0]='X'
t[2][1]='Y'
print t

#------------------------------------------------------
age = 20
if age >= 18:
print 'your age is', age
print 'adult'

age = 3
if age >= 18:
print 'your age is', age
print 'adult'
else:
print 'your age is', age
print 'teenager'

age = 3
if age >= 18:
print 'adult'
elif age >= 6:
print 'teenager'
else:
print 'kid'

names = ['Michael', 'Bob', 'Tracy']
for name in names:
print name

sum = 0
#for x in (1,2,3,4,5,6,7,8,9,10):
for x in range(101):
sum = sum + x
print sum

sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print sum

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print d['Michael']
d['Adam']=67
print d
#由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉:
d['Jack']=75
print d
d['Jack']=88
print d
print 'Jack' in d
print d.get('Jack')
d.pop('Jack')
print d

s = set([1, 1, 2, 2, 3, 3])
print s
s.add(4)
print s
s.add(3)
print s
s.remove(4)
print s
s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
print s1 & s2
print s1 | s2

#不可变对象
a = ['c','b','a']
a.sort()
print a
a='abc'
print a.replace('a','A')
print a
b = a.replace('a','A')
print b

#函数
print abs(100)
print abs(-20)
print unicode(100)

def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError('bad operand type')
if x>=0:
return x
else:
return -x
print my_abs(-20)
print my_abs(100)
#print my_abs('A')

import math
def move(x,y,step,angle=0):
nx=x+step*math.cos(angle)
ny=y-step*math.sin(angle)
return nx,ny

x,y=move(100,100,60,math.pi/6)
print x,y
#但其实这只是一种假象,Python函数返回的仍然是单一值,turple
r=move(100,100,60,math.pi/6)
print r

def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s

print power(5,2)
print power(5)

def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
print add_end()
print add_end()

def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc(1,2,3,4)
nums = [1,2,3,4,5]
print calc(*nums)

def person(name, age, **kw):
print 'name:', name, 'age:', age, 'other:', kw
print person('Michael', 30)
print person('Bob', 35, city='Beijing')
print person('Adam', 45, gender='M', job='Engineer')

def func(a, b, c=0, *args, **kw):
print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw
print func(1,2)
print func(1,2,c=3)
print func(1,2,3,'a','b')
print func(1,2,3,'a','b',x=99)
args = (1,2,3,4)
kw = {'x':99}
print func(*args,**kw)
#   *args是可变参数,args接收的是一个tuple;
#   **kw是关键字参数,kw接收的是一个dict。

#递归函数
def fact(n):
if n==1:
return 1
return n*fact(n-1)

print fact(5)

L=[]
n=1
while n<=99:
L.append(n)
n=n+2
print L

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print L[0:2] #不包括索引2
print L[:2]
print L[1:2]
print L[-2:]
L =range(100)
print L[:10]
print L[-10:]
print L[:10:2]
print L[::5]

d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print key
for value in d.itervalues():
print value

for ch in 'ABC':
print ch

for i, value in enumerate(['A', 'B', 'C']):
print i, value

from collections import Iterable
print isinstance('abc', Iterable)	# str是否可迭代
print isinstance([1,2,3], Iterable) # list是否可迭代
print isinstance(123, Iterable)	 	# 整数是否可迭代

#列表生成式
L = []
for x in range(1,11):
L.append(x*x)
print L
print [x*x for x in range(1,11)]
print [x*x for x in range(1,11) if x%2==0]
print [m+n for m in 'ABC' for n in 'XYZ']

#列出当前目录下的所有文件和目录名
import os
print [d for d in os.listdir('.')] #显然比下面更简洁
for d in os.listdir('.'):
print d

d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k,v in d.iteritems():
print k,'=',v

d = {'x': 'A', 'y': 'B', 'z': 'C' }
print [k+'='+v for k,v in d.iteritems()]
L = ['Hello', 'World', 'IBM', 'Apple']
print [s.lower() for s in L]

#生成器表达式,它并不创建一个列表,只是返回一个生成器
L= (i +1for i in range(10) if i %2)
print L

g=(i + 1 for i in range(10) if i % 2)
l=[]
for j in g:
l.append(j)
print l

#斐波拉契数列
def fib(max):
n,a,b = 0,0,1
while n<max:
print b
a,b = b,a+b
n=n+1

print fib(6)

def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
print fib(6)
for n in fib(6):
print n

#高阶函数
def add(x,y,f):
return f(x)+f(y)
print add(-5,-6,abs)

def f(x):
return x*x
print map(f,[1,2,3,4,5,6,7,8,9])

print map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]) #数字转字符串

#累加
def add(x,y):
return x+y
print reduce(add,[1,3,5,7,9])
#转换成13579
def fn(x,y):
return x*10+y
print reduce(fn,[1,3,5,7,9])

def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

#把str转换为int的函数:
print reduce(fn,map(char2num,'13579'))

def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
return reduce(fn, map(char2num, s))

#第一题:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']。
def normalize(s):
return s[0].upper()+s[1:].lower()
print map(normalize,['adam', 'LISA', 'barT'])
#第二题:python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积。
def prod(x,y):
return x*y
print reduce(prod,[2,4,6])

def prod2(a):
def calc(a,b):
return a*b
return reduce(calc,a)
print prod2([1,2,3,4,5])

#filter
def is_odd(n):
return n%2 ==1
print filter(is_odd,[1,2,3,4,5,6,7,8,9,10])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: