赞
踩
while 条件:
条件成立重复执行的代码1
条件成立重复执行的代码2
......
适用于次数不确定的程序,也可用于次数确定的程序。
i = 1
result = 0
while i <= 100:
result += i
i += 1
# 输出5050
print(result)
注意:为了验证程序的准确性,可以先改小数值,验证结果正确后,再改成1-100做累加。
from random import randint
num=randint(1,100)
# print(num)
while True:
n=int(input('你猜测的数字(1~100):'))
if num==n:
print('你猜对了')
break
elif num < n:
print('你的数字猜大了')
else:
print('你的数字猜小了')
break和continue是循环中满足一定条件退出循环的两种不同方式。break:结束所在循环,continue:结束其所在循环的本次循环。
i = 1
while i <= 5:
if i == 4:
print(f'吃饱了不吃了')
break
print(f'吃了第{i}个苹果')
i += 1
执行结果:
D:\ProjectSoftware\anacode\python.exe D:/ProjectFile/千峰/02-day/class.py
吃了第1个苹果
吃了第2个苹果
吃了第3个苹果
吃饱了不吃了
Process finished with exit code 0
i = 1
while i <= 5:
if i == 3:
print(f'大虫子,第{i}个不吃了')
# 在continue之前一定要修改计数器,否则会陷入死循环
i += 1
continue
print(f'吃了第{i}个苹果')
i += 1
执行结果:
D:\ProjectSoftware\anacode\python.exe D:/ProjectFile/千峰/02-day/class.py
吃了第1个苹果
吃了第2个苹果
大虫子,第3个不吃了
吃了第4个苹果
吃了第5个苹果
Process finished with exit code 0
for 循环执行次数根据容器中元素的个数决定
for循环每次执行,变量都会从该容器中按顺序获取元素
for 循环语法:
for 变量 in容器:
代码块
range(m,n,step):
设计步长的时候三个参数必写,否则会忽略默认为0.
num=0
for i in range(0,101,2):
num+=i
print(num)
for i in range(100,1,-1):
print(i)
循环可以和else配合使用,else下方缩进的代码指的是当循环正常结束之后要执行的代码。
for 临时变量 in 序列:
重复执行的代码
...
else:
循环正常结束之后要执行的代码
所谓else指的是循环正常结束之后要执行的代码,即如果是break终止循环的情况,else下方缩进的代码将不执行。
for i in range(2,101):
if i == 2:
print('2是素数')
else:
for j in range(2,i):#循环除以2到i里面的每一个数,查看是否有能除尽的
if i % j == 0:
print(f'{i}不是素数')
break
else:
print(f'{i}是素数')
镜像源:
清华:https://pypi.tuna.tsinghua.edu.cn/simple
豆瓣:http://pypi.douban.com/simple/
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
临时使用
pip install -i https://pypi.doubanio.com/simple/ pyspider
永久修改
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
包安装命令
pip install 包名 #苹果用pip3
# 方法二:
# 使用pycharm提供的可视化安装。
# widnows --> file -> settings -> project -> python interpreter -> +
# mac --> pycharm -> preferences -> project ->python interpreter -> +
# 进度条:tqdm(容器)
from tqdm import tqdm
# 有进度条就不能用打印,二存其一
for j in range(10):
for i in tqdm(range(1,100)):
pass
while 条件:
条件成立重复执行的代码1
条件成立重复执行的代码2
......
while 条件1:
条件1成立执行的代码
......
while 条件2:
条件2成立执行的代码
......
for 临时变量 in 序列:
重复执行的代码1
重复执行的代码2
......
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。