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

python之控制流

时间:2017-04-11 09:57:31      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:n+1   区别   计算   语句   条件判断   else   tin   trying   str   

条件判断

简单if语句

>>>name=‘lily‘
>>>if name=‘lily‘:
          print ‘hello,‘, name

hello,lily

if-else

>>>score=90
>>>if score>=80:
          print ‘very good‘
else:
    print ‘keep trying‘

very good

if-elif-else

>>> age=18
>>> if age>=18:
	print ‘adult‘
elif age<18:
	print ‘teenager‘
else:
	print ‘please enter the correct age‘

adult

循环

for

>>> L=[1,2,3,4,5]
>>> for v in L:
	print v

1
2
3
4
5

while

>>> a=0
>>> while a<10:
	a=a+1
	print a

1
2
3
4
5
6
7
8
9
10

退出循环

break与continue区别:

break:退出循环体

利用 while True 无限循环配合 break 语句,计算 1 + 2 + 4 + 8 + 16 + ... 的前20项的和。

>>> s = 0
>>> x = 1
>>> n = 1
>>> while True:
	if n>20:
		break
	s=s+x
	x=x*2
	n=n+1
	print s

	
1
3
7
15
31
63
127
255
511
1023
2047
4095
8191
16383
32767
65535
131071
262143
524287
1048575

continue:退出本次循环,不执行此次循环的循环体,继续下一个循环

>>> b=[0,1,2,6,3,4,1,5]
>>> for v in b:
	if v<2:
		continue
	print v

	
2
6
3
4
5

 

python之控制流

标签:n+1   区别   计算   语句   条件判断   else   tin   trying   str   

原文地址:http://www.cnblogs.com/evablogs/p/6691776.html

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