
一、if判断语句
1. if…else
if 条件:
满足条件时要做的事情1
满足条件时要做的事情2
……
else:
不满足条件时要做的事情1
不满足条件时要做的事情2
……
# -*- coding:utf-8 -*-
age = input("请输入年龄:")
age = int(age)
if age > 18:
    print("已经成年")
else:
    print("未成年")
2. elif
elif的使用格式如下:
if xxx1:
事情1
elif xxx2:
事情2
elif xxx3:
事情3
说明:
当xxx1满足时,执行事情1,然后整个if结束。
当xxx1不满足时,那么判断xxx2,如果xxx2满足,则执行事情2,然后整个if结束。
当xxx1不满足时,xxx2也不满足,如果xxx3满足,则执行事情3,然后整个if结束。
score = 66
if score>=90 and score<=100:
    print('本次考试,等级为A')
elif score>=80 and score<90:
    print('本次考试,等级为B')
elif score>=70 and score<80:
    print('本次考试,等级为C')
elif score>=60 and score<70:
    print('本次考试,等级为D')
elif score>=0 and score<60:
    print('本次考试,等级为E')
3. if嵌套
if嵌套的格式
if 条件1:
满足条件1 做的事情
if 条件2:
满足条件2 做的事情
说明:
内外层都可以是if-else语句
内外层的判断标准是tab缩进
# -*- coding:utf-8 -*-
ticket = 0 #车票,非0代表有车票,0代表没有车票
suitcase = 1 #手提箱,0代表检查合格,非0代表有违禁品
if ticket != 0:
    print("有车票,可以进站")
    if suitcase == 0:
        print("通过安检")
        print("终于可以见到Ta了,美滋滋~~~")
二、while循环
1. while循环的格式
while 条件:
条件满足时,做的事情1
条件满足时,做的事情2
条件满足时,做的事情3
# 计算1~100里所有偶数的和<br>i = 1
sum = 0
while i<=100:
    if i%2 == 0:
        sum = sum + i
    i+=1
print("1~100的累积和为:%d"%sum)
2. while嵌套
while 条件1:
条件1满足时,做的事情1
条件1满足时,做的事情2
while 条件2:
条件2满足时,做的事情1
条件2满足时,做的事情2
要求:打印如下图形:
* * * * * * * * * * * * * * *
i = 1
while i <= 5:
    j = 1
    while j <= i:
        # print默认用/n作为结束符,这里不能换行,重新指定结束符end=''
        print("* ", end='')
        j += 1
    # 这里使用默认的换行即可,不需要任何内容
    print()
    i += 1
3. while+else
与其它语言else 一般只与if 搭配不同,在Python 中还有个while …else 语句,while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句。
count = 0
while count <= 5 :
    count += 1
    print("Loop",count)
 
else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦
-----out of while loop ------
 
#如果执行过程中被break啦,就不会执行else的语句啦
count = 0
while count <= 5 :
    count += 1
    if count == 3:break
    print("Loop",count)
else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出
 
Loop 1
Loop 2
-----out of while loop ------
三、for循环
for 临时变量 in 列表或者字符串等:
循环满足条件时执行的代码
else:# 选择性使用
循环不满足条件时执行的代码
# 打印九九乘法表
for i in range(1, 10):
    for j in range(1, i + 1):
        print('%s*%s=%s' % (j, i, i * j), end=' ')
    print()
四、break和continue
#break用于退出本层循环 while True: print "123" break print "456" #continue用于退出本次循环,继续下一次循环 while True: print "123" continue print "456"
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试
 
                     
                


