码迷,mamicode.com
首页 > 编程语言 > 详细

Python循环_for&while

时间:2019-03-28 00:50:03      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:str   amp   int   输入   不执行   dash   sdi   ota   变量   

格式:for x in xs[‘James‘,‘Lily‘,‘Candy‘]:

                print(x)

——————————————————————————————————

for循环就是把每个元素代入变量x,执行for循环里面的代码

1 # -*- coding: utf-8 -*-
2 sum = 0
3 for x in range(101):
4     sum = sum + x
5 print(sum)

_______________________________________________________________________________

while循环,满足条件,就循环,不满足即退出

1 # -*- coding: utf-8 -*-
2 sum = 0
3 t_times = 100
4 while t_times >0 :
5     sum = sum + t_times
6     t_times =t_times -1
7 print(sum)

_______________________________________________________________________

break语句,跳出循环,可以设定跳出条件

1 sum = 0
2 for x in range(10):
3     sum = sum + x
4     if sum >= 10:
5         break
6 print(sum)

continue语句,路过当前循环(continue以下的代码均不执行),例(计算1-100的单数相加的和):

 1 #! -*-coding:utf-8 -*-
 2 
 3 def sum_of_odd():
 4     total = 0
 5     content = input("计算基数总和,请输入整数最大值:")
 6     if content.isdigit():
 7         t_times = int(content)
 8     else:
 9         print("请输入正确的类型!")
10         return sum_of_even()
11 
12     while t_times > 0:
13         if t_times % 2 == 0:
14             t_times = t_times - 1
15             continue
16         print("相加的基数为:" + str(t_times))
17         total = total + t_times
18         if t_times > 0:
19             t_times = t_times - 1
20         else:
21             pass
22     print("在此范围内的基数相加和为:" + str(total))
23 
24 sum_of_odd()

 

Python循环_for&while

标签:str   amp   int   输入   不执行   dash   sdi   ota   变量   

原文地址:https://www.cnblogs.com/iamjames/p/10611915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!