这是我自己在学习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