Conditions and loops for Python basic learning code
Def func1 (): alist = ['Cathy ', 'Terry', 'Joe ', 'health', 'Lucy'] for I in range (-1, -len (alist)-1,-1): print I, alist [I] def func2 (): alist = ['Cathy ', 'Terry', 'Joe ', 'health', 'Lucy '] for I, name in enumerate (alist): print' % d % s' % (I, name) import randomdef func3 (): alist = ['Cathy ', 'Terry', 'Joe ', 'health', 'Lucy'] blist = [random. randint (I, 10) for I in range (5)] for a, B in zip (alist, blist): print a, bdef func4 (): num = 4 count = num/2 while count> 0: if num % count = 0: print count, 'is the largest factor ', num break count-= 1def showmaxfactor (num): count = num/2 while count> 1: if num % count = 0: print num, 'largest factor is ', count break count-= 1 return True else: print num, is prime 'return Falsedef func5 (): for eachnum in range (): showmaxfactor (eachnum) def func6 (): alist = range (5) return map (lambda x: x ** 2, alist) def func7 (): alist = [x ** 2 for x in range (5)] return alistdef func8 (): return filter (lambda x: x % 2, range (10) def func9 (): return [x for x in range (10) if x % 2] def func10 (): return [(x + 1, y + 1) for x in range (3) for y in range (5)] import osdef func11 (): f = open ('client. PY', 'r') print OS. stat ('client. py '). st_size print len ([word for line in f for word in line. split ('')]) f. seek (0) print sum ([len (word) for line in f for word in line. split ('')]) def cols (): yield 3 yield 5def func12 (): alist = [1, 2, 4, 6] x = (I, j) for I in alist for j in cols () for a in x: print adef func13 (): f = open ('client. PY', 'r') longest = 0 alllines = f. readlines () f. close () for line in alllines: linelen = len (line. strip () if linelen> longest: longest = linelen return longestdef func14 (): f = open ('client. PY', 'r') alllinelen = [len (x. strip () for x in f] f. close () return max (alllinelen) def func15 (): return max (len (x. strip () for x in open ('client. PY', 'r') def func16 (x, y, z): alist = [] for I in range (x, y + 1, z): alist. append (I) return alistdef getfactors (num): for I in range (1, num + 1): if num % I = 0: print idef isperfect (num ): sum = 0 count = num/2 while count> 0: for I in range (1, count + 1): if num % I = 0: sum + = I count-= 1 if sum = num: return True else: return Falsedef fig (num): if num = 1: return [1] if num = 2: return [1, 1] list = [1, 1] if num> 2: for I in range (3, num + 1): list. append (list [-1] + list [-2]) return listdef convert (): start = int (raw_input (u' enter the start value :')) end = int (raw_input (u' enter the end value: ') for I in range (start, end + 1 ): print "dec bin oct hex" print '-' * 20 print "% d % s" % (I, bin (I), oct (I ), hex (I ))
The above is the condition and loop content of the Python basic learning code. For more information, see The PHP Chinese website (www.php1.cn )!