Python学习笔记-循环语句(For、While)

Python学习笔记-循环语句(For、While)

这是我自己在学习Python过程中的学习笔记,参考资料为菜鸟笔记、相关学习视频、书籍

For

for 循环可以遍历任何可迭代对象,如一个列表、字符串、字典

for <variable> in <sequence>:
    <statements>
else:
    <statements>
#列表
songs =['song1','song2','song3','song4']
for song in songs:
    #song =songs[0]
    print('正在播放:{}'.format(song))
    #index +1

#字符串
name = 'ni hao xin nian kuai le '
for i in name:
    print(i,end='/')

**************执行结果***********
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
正在播放:song1
正在播放:song2
正在播放:song3
正在播放:song4
n/i/ /h/a/o/ /x/i/n/ /n/i/a/n/ /k/u/a/i/ /l/e/ /

Process finished with exit code 0

# 字典
# 字典默认是获取keys
name={'name':'xiaopang','age':18,'hobby':'ball'}
for i in name:
    print(i)
for t in name.keys():
    print(t)
for f in name.values():
    print(f)

for i,f in name.items():
    print(i,f)
    
*************执行结果**********
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
name
age
hobby
name
age
hobby
xiaopang
18
ball
name xiaopang
age 18
hobby ball

Process finished with exit code 0
  • for嵌套循环
list1 = [4,5,6]
list2 = [2,3,4]
for v1 in list1:
    for v2 in list2:
        print("{}*{}={}".format(v1,v2,v1*v2))

************执行结果***************
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
4*2=8
4*3=12
4*4=16
5*2=10
5*3=15
5*4=20
6*2=12
6*3=18
6*4=24

Process finished with exit code 0

While

While格式如下,同样需要注意冒号和缩进

while 判断条件(condition):
    执行语句(statements)……

示例:

#while
# 打印10次的 “我喜欢旅行”
# while (条件表达式)

i=0
while (i<10):
     print('我喜欢旅行')
     print(i)
     i +=1

print ('开始去旅行')
#打印10次我喜欢旅行后开始去旅行

*************执行结果************
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
我喜欢旅行
0
我喜欢旅行
1
我喜欢旅行
2
我喜欢旅行
3
我喜欢旅行
4
我喜欢旅行
5
我喜欢旅行
6
我喜欢旅行
7
我喜欢旅行
8
我喜欢旅行
9
开始去旅行

Process finished with exit code 0
  • 退出While的方式
#退出while的方式
a=0
while True:
    if a==10:
        print('我喜欢xx')
        print(a)
        # 手工终止程序
        break
     # 退出这一个条件,进入下一个分支
    a+=1
print('得偿所愿')

**************执行结果*******************
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
我喜欢xx
10
得偿所愿

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值