python学习记录 — (3)条件语句与循环语句

ConditionalAndLoopStatement.py

#coding=utf-8

#################################### python条件语句 ####################################

a,b,c = 1,2,0

# if 语句

if a and b:
    print (a and b)                                     # 2

if b and c:   # python认为0为false,此处返回0
    print (b and c)

# if else 语句

if a and c:
    print (a and c)
else:
    print (not(a and c))                                # True

if a and c:
    print(a and c)
elif b and c:
    print(b and c)
else:
    print(not(a and c) and not(b and c))                # true

# if 嵌套语句

if a or c:
    print ("a or c = true")                             # a or c = true
    if c or b:
        print ("c or b = true")                         # c or b = true

#################################### python循环语句 ####################################

# while 循环(循环可以使用else)

a = 0
while (a<5):
    print("a = " + str(a))                                  # a = 0/1/2/3/4
    a = a + 1
else:   # 当退出循环时,执行1次;
    print ("退出while循环")                                 # 退出while循环

# for 循环(循环可以使用else)
for k,v in {'lua':5.1,'python':2.7,'c++':11}.items():
    print 'key:{k},value{v}'.format(k=k,v=v)                # key:python,value2.7/key:lua,value5.1/key:c++,value11
for index in [1,2,"python"]:
    print (index)                                           # 1/2/python
for index in "hello":
    print index                                             # h/e/l/l/o
for index in range(0,5,1):
    print index                                             # 0/1/2/3/4
else:   # 当退出循环时,执行1次;
    print ("退出for循环")                                   # 退出for循环

# 嵌套循环(代码块是根据严格的空格来区分的)

for i in range(5):
    while i==3:
        j = 0
        while j<=5:
            print "j =",j                                  # j = 0/1/2/3/4/5
            j+=1
        i = i+1

# break 语句(用与打破for或while循环)

while True:
    print("这里使用break")                                  # 这里使用break
    break

# continue 语句

i = 1
while i <10:
    i += 1
    if i%2 > 0:
        continue
    print i                                                 # 2/4/6/8/10

# pass 语句(是空语句,为了保持程序结构的完整性,即不做任何事)

i = 1
while i>0:
    print "这里使用pass"                                    # 这里使用pass
    pass
    i -= 1


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值