Python入门之for循环语句及其简单练习 |
您所在的位置:网站首页 › python循环语句例题 › Python入门之for循环语句及其简单练习 |
1 for循环语句格式
1.1 for循环语句格式: """ for循环语法: for 变量 in range(x): 循环需要执行的代码 """ """ range(stop): 0 ~ stop-1 range(start,stop): start ~ stop-1 range(start,stop,step): start ~ stop-1 step(步长) """ # print(range(1,10,2)) [root@foundation72 ~]# python Python 2.7.5 (default, Aug 2 2016, 04:20:16) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> range(5) [0, 1, 2, 3, 4] >>> range(1,15) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> range(1,15,3) [1, 4, 7, 10, 13] >>>1.2 break、continue、exit(): """ break:跳出整个循环,不会再执行循环后面的内容 continue:跳出本次循环,continue后面的代码不再执行,但是循环依然继续 exit():结束程序的运行 """ for i in range(10): if i == 5: # continue # break exit() print('hello') print(i) print('hello python')break控制:
1.3 for循环语句练习一: #1~100之间的所有偶数求和(奇数和类似,range(1,100,2)) sum = 0 for i in range(2,101,2): sum += i print(sum) #求输入数字的阶乘 num = int(input('Num:')) res = 1 for i in range(1,num+1): res *= i print('%d的阶乘结果为: %d' %(num,res))
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |