Python基础学习笔记(自用)(3)

一、分支结构

单分支结构

if<条件>:
            <语句块>

二分支结构

 if<条件>:
 	<语句块>
 else: 
 	<语句块>

紧凑形式:“对” if guess==99 else “错”

多分支结构

if<条件>:
	<语句块>
elif<条件>:
	<语句块>
else:         
	<语句块>

二、循环结构

遍历循环

for<循环变量> in <遍历结构>:
    	<语句块>

1.计数循环:

for i in range(N):
    	<语句块>

例如:for i in range(5):
print(i)------------0,1,2,3,4

例如:for i in range(1,6):
print(i)-----------1,2,3,4,5

2. 字符串遍历循环:

    for  c in s:
    	<语句块>

例如:for c in “Python”:
print(c,end=",")-----P,y,t,h,o,n

3.列表遍历循环:

     for item in ls:
     	<语句块>

例如:for item in[1,“hel”,2]:
print(item,end=",")--------1,hel,2

4.文件遍历循环:

    for line in fi :
    	<语句块>-----遍历文件的每一行

无限循环

    while <条件>:
    	<语句块>

例如:a=3
while a>0:
a=a-1
print(a)------2,1,0

若程序执行陷入无限循环中,可用CTRL+c退出

循环控制保留字

break :跳出并结束当前整个循环,执行循环后的语句
continue:结束当次循环,继续执行后续次数循环

例1: for c in “Python”:
if c==‘t’:
continue
print(c,end="")------Pyhon

例2 : for c in “Python”:
if c==‘t’:
break
print(c,end="")------Py

循环与else的搭配

          for <循环变量> in <遍历结构>:
          		<语句块1>
          else:
           		<语句块2>
          while<条件>:
       		<语句块1>
           else:
       		<语句块2>

例一: for c in “Python”:
if c==‘t’:
continue
print(c,end="")
else:
print(“正常退出”)------Pyhon正常退出
例二:for c in “Python”:
if c==‘t’:
break
print(c,end="")
else:
print(“正常退出”)------Py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值