python分支和循环

python可以有效避免悬挂else
python不存在悬挂else(else就近原则,else属于内层if),强制使用正确的缩进
条件表达式
三元操作符语法:
a = x if 条件 else y
ex:

if x < y:
small = x
else:
small = y

==> small = x if x < y else y

断言(assert)
当关键字后边的条件为假时,程序自动崩溃并抛出AssertionError的异常
Traceback (most recent call last): File "F:/PythonPrj/demo1/fishc/p4_1.py", line 12, in <module> assert 3 >4 AssertionError
一般来说,可以用它在程序中置入检查点,当需要确保程序中的某个条件一定为真才能让程序正常工作时,assert关键字就非常有用了。

while循环语句
while条件:
循环体
for循环语句
比C语言的更加只能和强大
它会自动调用迭代器的next()方法,会自动捕获StopIteration异常并结束循环。

favourite = “羽生结弦”
for each in favourite:
print(each,end = " ")
羽 生 结 弦

range()
for的小伙伴,元组和列表
语法:range([start,]stop[,step = 1])
生成一个从start参数的值开始,到stop参数的值结束的数字序列。常与for虚幻混迹于各种技术循环之间。

for i in range(5):
    print(i)
    0
    1
    2
    3
    4
for i in range(2,5):
    print(i)
    2
    3
    4
for i in range(1,10,2):
    print(i)
    1
    3
    5
    7
    9

break
终止当前循环,跳出循环体

bingo = "羽生结弦牛逼!"
answer = input("请输入你的赞美:")
while True:
    if answer == bingo:
        break
    answer = input("抱歉,错了,请重新输入(答案正确才能退出游戏):")
print("回答正确")

continue
终止本轮循环,开始下一轮循环(在开始下一轮之前,会先测试循环条件)

for i in range(10):
     if i % 2 !=0:
        print(i)
        continue
     i += 2
     print(i)
2
1
4
3
6
5
8
7
10
9

猜你喜欢

转载自blog.csdn.net/weixin_41130372/article/details/84666664