1. Achieve 1-100 of all and
def qiuhe (x, y):
return x + y
he = 0
For I in Xrange (1, 101):
He =qiuhe (he,i)
Print (He)
2. Achieve 1-500 of all odd and
def is_odd (x):
return x% 2 = = 1
def qiuhe (x, y):
return x + y
he = 0
For I in Filter (Is_odd,xrange (1,501)):
Print (i)
he = Qiuhe (He, I)
Print (He)
3. Ask for 1+ 2! + 3! + 4! + ... 20! and the
def qiuhe (x, y):
return x + y
def Jiecheng (n):
if (n<=1):
Return 1
Else
Return Jiecheng (n-1) *n
he = 0
For I in Xrange (1, 21):
He +=jiecheng (i)
Print (He)
4. Sort the specified list [2,32,43,453,54,6,576,5,7,6,8,78,7,89]
List.sort () is sorted locally and does not return a copy
Or
def cmp_value (x, y):
If x > Y:
Return 1
Elif x < y:
Return-1
Else
return 0
LISTSORTED=[2,32,43,453,54,6,576,5,7,6,8,78,7,89]
So=sorted (Listsorted,cmp=cmp_value)
Print (SO)
5. Dictionary sorting, string, list, tuple common methods
Dictionary sort:
Import operator
D = {' Data1 ': 3, ' data2 ': 1, ' data3 ': 2, ' DATA4 ': 4}
Print (sorted (D.iteritems (), Key=operator.itemgetter (1))
List
classmates = [' Michael ', ' Bob ', ' Tracy ']
#len
Print (len (classmates))
#index
Print (Classmates[0])
#-1
Print (Classmates[-1])
#append
Classmates.append (' Adam ')
Print (classmates)
#insert
Classmates.insert (1, ' Jack ')
Print (classmates)
#pop
Classmates.pop (1)
Print (classmates)
Python Exercises (i)