Python基础学习代码之条件和循环
程序员文章站
2022-06-02 19:37:36
...
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 random def 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,b def func4(): num = 4 count = num / 2 while count > 0: if num % count == 0: print count,'is the largest factor of',num break count -= 1 def 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 False def func5(): for eachnum in range(10,60): 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 alist def 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 os def 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 5 def func12(): alist = [1,2,4,6] x = ((i,j) for i in alist for j in cols()) for a in x: print a def 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 longest def 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 alist def getfactors(num): for i in range(1,num+1): if num % i == 0: print i def 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 False def fibonacci(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 list def convert(): start = int(raw_input(u'请输入起始值:')) end = int(raw_input(u'请输入结束值:')) for i in range(start,end+1): print "dec bin oct hex" print '-' * 20 print "%d %s %s %s" % (i,bin(i),oct(i),hex(i))
以上就是Python基础学习代码之条件和循环的内容,更多相关内容请关注PHP中文网(www.php.cn)!
推荐阅读
-
Python3.4学习笔记之常用操作符,条件分支和循环用法示例
-
Python3.5基础之变量、数据结构、条件和循环语句、break与continue语句实例详解
-
Python3.4学习笔记之常用操作符,条件分支和循环用法示例
-
Python3基础之条件与循环控制实例解析
-
python人脸识别项目之基础学习(三):矩阵的基本运算 + 张量的阶和形态
-
零基础学习01(条件,循环和其他语句 )
-
.Net程序员之Python基础教程学习----判断条件与循环[Fourth Day]
-
python基础、字符串和if条件语句,while循环,跳出循环、结束循环
-
Python3.5基础之变量、数据结构、条件和循环语句、break与continue语句实例详解
-
python学习基础之循环import及import过程