python的语句

来源:互联网 发布:编程语言效率排行 编辑:程序博客网 时间:2024/05/22 11:59

python的缩进

python所有的逻辑都是按空格或者tab来区分的,如果你是单人开发你可以选择用2个空格或者tab键来作为缩进单位,但是多人协作开发建议统一使用四个空格,并且为了防止tab和空格混淆,请在IDE中将tab设置为4个空格

if语句

一般形式:(python不支持case语句,因此用if-elif完成)

age = 20if age >= 18:    print  'adult'elif age >= 6:    print 'teenager'else:    print 'kid'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

简略形式:

if age:    print 'ture'elseprint ‘none’
  • 1
  • 2
  • 3
  • 4

三元操作: 
x if x

for语句

sum=0for x in range(101):              #range(101) 会生成0-100的序列。    sum = sum + xelse:                                      #正常退出循环时,执行else后面的语句。若提前break,则不执行。    print sumenumerate可以同时计数循环次数和打印循环结果:data=[123,456,'abc']for i,value in enumerate(data):    print i,value>>0 1231 4562 abc
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

while语句

一般形式:

sum = 0n = 99while n > 0:    sum = sum + n    n = n - 2print sum
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

continue,break

break语句用来终止循环,即使条件没有执行完,也会停止循环语句,跳出整个循环, 
continue只会跳出本次循环

//i=3的时候终止循环for i in xrange(1,5):  if i==3:   print(‘hello word’)   breakprint(‘i = %d%i)i = 1i = 2hello word//不打印3for i in xrange(1,5):  if i==3:   print(‘hello word’)   continueprint(‘i = %d%i)i = 1i = 2hello wordi = 4i = 5
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
原创粉丝点击