#! python
# Fibonacci series:
# the sum of two elements defines the next
a,b=0,1whileb<200:printb,a,b=b,a+b#! python
# input and operator if
x=int(raw_input("Please enter an integer: "))ifx<0:x=0print'Negative changed to zero'elifx==0:print'Zero'elifx==1:print'Single'else:print'More'#! python
# operator for:
# Measure some strings:
a=['cat','window','defenestrate']forxina:printx,len(x)#! python
# range function
printrange(10)printrange(5,10)printrange(0,10,3)a=['Mary','had','a','little','lamb']foriinrange(len(a)):printi,a[i]#! python
# break operator
# prime numbers
forninrange(2,1000):forxinrange(2,n):ifn%x==0:printn,'equals',x,'*',n/xbreakelse:# loop fell through without finding a factor
printn,'is a prime number'
#! python
#pass statement does nothing.
#It can be used when a statement is required syntactically but the program requires no action. For example:
whileTrue:pass# Busy-wait for keyboard interrupt
#! python
# Defining Functions
deffib(n):# write Fibonacci series up to n
"""Print a Fibonacci series up to n."""a,b=0,1whileb<n:printb,a,b=b,a+b# Now call the function we just defined:
fib(2000)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
!python# function that returns a list of the numbers of the Fibonacci series
deffib2(n):# return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""result=[]a,b=0,1whileb<n:result.append(b)# see below
a,b=b,a+breturnresult#===================================
f100=fib2(100)# call it
printf100# write the result
#! python
# work with strings
# Strings can be concatenated (glued together) with the + operator, and repeated with *:
word='Help'+'A'printwordprint'<'+word*5+'>'# Two string literals next to each other are automatically concatenated;
# the first line above could also have been written "word = 'Help' 'A'";
# this only works with two literals, not with arbitrary string expressions:
st='str''ing'# <- This is ok
printstst='str'.strip()+'ing'# <- This is ok
printst# Strings can be subscripted (indexed); like in C, the first character of a string
# has subscript (index) 0. There is no separate character type; a character is
# simply a string of size one. Like in Icon, substrings can be specified with
# the slice notation: two indices separated by a colon.
printword[4]printword[0:2]printword[2:4]# Slice indices have useful defaults; an omitted first index defaults to zero,
# an omitted second index defaults to the size of the string being sliced.
printword[:2]# The first two characters
printword[2:]# All but the first two characters
# Python strings cannot be changed. Assigning to an indexed position in the string results in an error:
# However, creating a new string with the combined content is easy and efficient:
print'x'+word[1:]print'Splat'+word[4]# Here's a useful invariant of slice operations: s[:i] + s[i:] equals s.
printword[:2]+word[2:]printword[:3]+word[3:]# Degenerate slice indices are handled gracefully: an index that is too large is replaced
# by the string size, an upper bound smaller than the lower bound returns an empty string.
printword[1:100]printword[10:]printword[2:1]# Indices may be negative numbers, to start counting from the right. For example:
printword[-1]# The last character
printword[-2]# The last-but-one character
printword[-2:]# The last two characters
printword[:-2]# All but the last two characters
# But note that -0 is really the same as 0, so it does not count from the right!
printword[-0]# (since -0 equals 0)
# Out-of-range negative slice indices are truncated, but don't try this for single-element (non-slice) indices:
printword[-100:]# print word[-10] # error
#The best way to remember how slices work is to think of the indices as pointing between characters,
#with the left edge of the first character numbered 0. Then the right edge of the last character
#of a string of n characters has index n, for example:
# +---+---+---+---+---+
# | H | e | l | p | A |
# +---+---+---+---+---+
# 0 1 2 3 4 5
#-5 -4 -3 -2 -1
s='supercalifragilisticexpialidocious'printsprintlen(s)
#! python
# Lambda Forms
defmake_incrementor(n):returnlambdax:x+n#==================================
f=make_incrementor(42)printf(0)printf(1)printf(15)//===================================================================================////===================================================================================#! python
# speed test
nn=10000000i=0;s=0;print"beginning..."whilei#! python
# raw input of strings only!
st=raw_input("")printstst=st*3# triple the string
printst#! python
# math
importmathprintmath.cos(math.pi/4.0)printmath.log(1024,2)
#! python
# random
importrandomprintrandom.choice(['apple','pear','banana'])printrandom.sample(xrange(100),10)# sampling without replacement
printrandom.random()# random float
printrandom.randrange(6)# random integer chosen from range(6)
#! python
defperm(l):# Compute the list of all permutations of l
iflen(l)<=1:return[l]r=[]# here is new list with all permutations!
foriinrange(len(l)):s=l[:i]+l[i+1:]p=perm(s)forxinp:r.append(l[i:i+1]+x)returnr#==============================================
a=[1,2,3]printperm(a)#! python
a=2+3jb=2-3jprinta*aprinta*bprinta.realprintb.imag#! python
whileTrue:try:x=int(raw_input("Please enter a number: "))breakexceptValueError:print"Oops! That was no valid number. Try again..."#! python
importstring,systry:f=open('myfile.txt')s=f.readline()i=int(string.strip(s))exceptIOError,(errno,strerror):print"I/O error(%s): %s"%(errno,strerror)exceptValueError:print"Could not convert data to an integer."except:print"Unexpected error:",sys.exc_info()[0]raise
#! python
# work with lists
a=['spam','eggs',100,1234]print" list a=",a# list indices start at 0,
print'a[0]=',a[0]print'a[3]=',a[3]print'a[-2]=',a[-2]# lists can be sliced, concatenated and so on:
print"a[1:-1]=",a[1:-1]printa[:2]+['bacon',2*2]print3*a[:3]+['Boe!']# possible to change individual elements of a list:
a[2]=a[2]+23print"changing a[2]=",a#Assignment to slices is also possible, and this can even change the size of the list:
# Replace some items:
a[0:2]=[1,12]printa# Remove some:
a[0:2]=[]printa# Insert some:
a[1:1]=['bletch','xyzzy']printaa[:0]=a# Insert (a copy of) itself at the beginning
printaprint"length=",len(a)# possible to nest lists (create lists containing other lists)
q=[2,3]p=[1,q,4]print" nest list=",pprint'length =',len(p)printp[1]printp[1][0]p[1].append('xtra')printpprintq#! python
# more work with lists
a=[66.6,333,333,1,1234.5]printa.count(333),a.count(66.6),a.count('x')a.insert(2,-1)printaa.append(333)printaprinta.index(333)a.remove(333)printaa.reverse()printaa.sort()printa#! python
# huge list making
nn=1000000a=[]i=0whilei#! python
# Using Lists as Stacks
stack=[3,4,5]stack.append(6)stack.append(7)printstackx=stack.pop()print"popped ",xprintstackx=stack.pop()print"popped ",xx=stack.pop()print"popped ",xprintstack#! python
# Using Lists as Queues
queue=["Eric","John","Michael"]queue.append("Terry")# Terry arrives
queue.append("Graham")# Graham arrives
printqueues=queue.pop(0)printss=queue.pop(0)printsprintqueue
#! python
# The del statement
a=[-1,1,66.6,333,333,1234.5]dela[0]printadela[2:4]printa#! python
# filter of sequence
deff(x):returnx%2!=0andx%3!=0res=filter(f,range(2,25))printres#! python
# map of sequence
defcube(x):returnx*x*xres=map(cube,range(1,11))printres#! python
# reduce(func, sequence)" returns a single value constructed by
# calling the binary function func on the first two items of the sequence,
# then on the result and the next item, and so on
defadd(x,y):returnx+yr=reduce(add,range(1,11))printr# 55
1
2
3
4
5
6
7
8
9
10
11
12
13
#! python
# A tuple consists of a number of values separated by commas
t=12345,54321,'hello!'# tuple packing
printt[0]printt(12345,54321,'hello!')# Tuples may be nested:
u=t,(1,2,3,4,5)printu# ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
#! python
# Dictionaries are sometimes as ``associative memories'' or ``associative arrays''
tel={'jack':4098,'sape':4139}tel['guido']=4127printtelprinttel['jack']deltel['sape']tel['irv']=4127printtelprinttel.keys()x=tel.has_key('guido')printx# The dict() constructor builds dictionaries directly from lists
# of key-value pairs stored as tuples. When the pairs form a pattern,
# list comprehensions can compactly specify the key-value list.
d=dict([('sape',4139),('guido',4127),('jack',4098)])printdvec=[1,2,3,4,5]dd=dict([(x,x**2)forxinvec])# use a list comprehension
printdd
#! python
# Standard Module sys
importsysprintsys.pathsys.path.append('c:\temp')printsys.pathprintsys.versionprintsys.platformprintsys.maxint#! python
#=======================================================
# dir() is used to find out which names a module defines
importsysprintdir(sys)# Without arguments, dir() lists the names you have defined currently
#! python
# convert any value to a string: pass it to the repr() or str()
s='Hello, world.'printstr(s)printrepr(s)printstr(0.1)printrepr(0.1)x=10*3.25y=200*200s='The value of x is '+repr(x)+', and y is '+repr(y)+'...'prints# The repr() of a string adds string quotes and backslashes:
hello='hello, world\n'hellos=repr(hello)printhellos# 'hello, world\n'
# The argument to repr() may be any Python object:
printrepr((x,y,('spam','eggs')))# reverse quotes are convenient in interactive sessions:
print`x, y, ('spam', 'eggs')`
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#! python
# two ways to write a table of squares and cubes:
forxinrange(1,11):printrepr(x).rjust(2),repr(x*x).rjust(3),# Note trailing comma on previous line
printrepr(x*x*x).rjust(4)print'================================================='forxinrange(1,11):print'%2d %3d %4d'%(x,x*x,x*x*x)
1
2
3
4
5
6
7
#! python
# output results from running "python demo.py one two three"
# at the command line:
importsysprintsys.argv[]# ['demo.py', 'one', 'two', 'three']
#! python
# String Pattern Matching - regular expression
importrer=re.findall(r'\bf[a-z]*','which foot or hand fell fastest')printr# ['foot', 'fell', 'fastest']
s=re.sub(r'(\b[a-z]+) \1',r'\1','cat in the the hat')prints# 'cat in the hat'
#! python
# dates are easily constructed and formatted
fromdatetimeimportdatenow=date.today()printnowdatetime.date(2003,12,2)printnow.strftime("%m-%d-%y or %d%b %Y is a %A on the %d day of %B")# dates support calendar arithmetic
birthday=date(1964,7,31)age=now-birthdayprintage.days# 14368
#! python
# Internet Access
importurllib2forlineinurllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):if'EST'inline:# look for Eastern Standard Time
printlineimportsmtplibserver=smtplib.SMTP('localhost')server.sendmail('soothsayer@tmp.org','jceasar@tmp.org',"""To: jceasar@tmp.org
From: soothsayer@tmp.org
Beware the Ides of March.
""")server.quit()
# work with files
#open file for write
f=open('c:/TEMP/workpy.txt','w')printff.write("aaaaaaaaaaaaaaaaaaa\n")f.write("bbbbbbbbbbbbbb");# work with files
#open file for read
f=open('c:/TEMP/workpy.txt','r')# line reading
s=f.readline()printsf.close()# work with files
#open file for read
f=open('c:/TEMP/workpy.txt','r')# pieces reading
s1=f.read(5)prints1s2=f.read(19)prints2s2=f.read(25)prints2f.close()# work with files
#open file for read
f=open('c:/TEMP/workpy.txt','r')# pieces reading
s1=f.read(5)prints1printf.tell()s2=f.read(19)prints2printf.tell()s2=f.read(25)prints2printf.tell()f.close()# work with files
# seek
f=open('c:/TEMP/workpy.txt','r+')f.write('0123456789abcdef')f.seek(5)# Go to the 6th byte in the file
printf.read(1)f.seek(-3,2)# Go to the 3rd byte before the end
printf.read(1)
1
2
3
4
5
6
7
8
9
#! python
# The glob module provides a function for making file lists from
# directory wildcard searches:
importglobs=glob.glob('*.*')prints# ['primes.py', 'random.py', 'quote.py']
← previous You can also navigate with left [or] right arrows next →