1.循环的语法与基本使用
while 条件:
代码1
代码2
代码3
例如:输出0~4
count = 0
while count < 5:
print(count)
count += 1
2.死循环与效率问题
#纯计算无IO的死循环会导致致命的效率问题
while True:
1 + 1
3.循环的应用
- 输出1~100的自然数
count = 1
flag = True
while flag:
print(count)
count = count +1
if count == 101:
flag = False
注意点:python中是没有++和--的,自加自减使用count +=1(count = count+1)
- 输出1~100的和
s = 0
count = 1
while count < 101
s = s + count
count = count +1
print(s)
- 输出1~100的偶数
count = 1
while count < 101:
if count % 2 ==0:
print(count)
count = count + 1
4.循环终止
- 将条件改为False,等到下次循环判断条件时才会生效
flag = True
while flag:
flag = False
print('狼的诱惑')
print('月亮之上')
print('庐州月')
- break:循环中遇到break直接退出循环
while True:
print('狼的诱惑')
print('我们不一样')
print('月亮之上')
break
print('庐州月')
print('人间')
5.continue
continue:结束本次循环,进入下一次
强调:在continue之后添加同级代码毫无意义,因为永远无法运行
flag = True
while flag:
print('111')
print('222')
flag = False
continue
print('333') # 111 222
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue
print(number) #13579
number = 0
while number < 10:
number += 1
if number % 2 == 0:
print(number) #246810
6.while else
while 循环如果被break打断,则不执行else语句
while True:
...
else:
print('else包含的代码会在while循环结束后',
并且while循环在没有被break打断的情况下才会运行)
count = 1
while (count < 5):
print (count)
if count == 2:
break
count = count + 1
else:
print('666') #1 2
7.例题:三次账号密码输入
count = 1
while count <= 3:
username = input('用户名:')
password = input('密码:')
code = 'qwer'
your_code = input('验证码:')
if your_code == code:
if username == ('alex') and password == ('123'):
print('登录成功')
break
else:
print('用户名或密码错误')
else:
print('验证码错误')
count = count + 1
成功则跳出本次循环