Day1:循环语句(While,For)
2024-08-31 17:07:41
一、while循环
while 条件:
条件为真执行的语句
esle:
条件为假执行的语句
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
count = 0
while count < 100:
print("Count:",count)
count += 1
猜年龄升级版
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
age_of_MrWang = 48
count = 0
while count < 3:
guess_age = int(input("Enter the age of Mr Wang:"))
if guess_age == age_of_MrWang:
print("Yes,you got it!")
break
elif guess_age < age_of_MrWang:
print("Think bigger!")
else:
print("Think smaller!")
count += 1
# if count == 3:
# print("You have tried too many times...Fuck off!")
else:
print("You have tried too many times...Fuck off!")
二、For循环
for i in range (xx):
语句
else:
上面循环里的语句正常走完了后,才执行这里的语句
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
for i in range(10):
print("loop",i)
再次优化一下猜年龄小程序
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
age_of_MrWang = 48
for i in range (3):
guess_age = int(input("Enter the age of Mr Wang:"))
if guess_age == age_of_MrWang:
print("Yes,you got it!")
break
elif guess_age < age_of_MrWang:
print("Think bigger!")
else:
print("Think smaller!")
else:
print("You have tried too many times...Fuck off!")
三、for循环步长问题
range里可以设置,默认是1
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
for i in range(0,10,2): #步长是2
print("loop",i)
四、猜年龄小程序加入继续玩模式
思路:猜了三次还没有猜对,提示是否继续猜,如果按n就退出程序,其他键就继续猜。同时判断输入是否为数字
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
age_of_MrWang = 48
count = 0 #计数器
while count < 3:
guess_age = input("Enter the age of Mr Wang:")
if guess_age.isdigit(): #输入了数字
guess_age = int(guess_age)
if guess_age == age_of_MrWang:
print("Yes,you got it!")
break #猜对了,退出while循环
elif guess_age < age_of_MrWang:
print("Think bigger!")
else:
print("Think smaller!")
count += 1
if count == 3:
continue_confirm = input("Do you want to keey guessing?")
if continue_confirm != "n":
count = 0 # 计数器清零
else:
print("Please enter a number!")
五、break与continue
continue:跳出本次循环(或者说:结束当前循环),继续下一次循环
break:结束整个循环
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
for i in range(0,10):
if i < 5:
print("loop",i)
else:
continue
print("The variable i loops once")
六、for循环嵌套
注意break的使用
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
for i in range(10):
print("-------",i)
for j in range (10):
print(j)
if j > 5:
break #结束当前循环(j),继续下一次循环
最新文章
- Android Studio :enable vt-x in your bios security,已经打开还是报错的解决方法
- TCP协议
- Python学习之路--面向对象
- Oracle_spatial的函数介绍[转]
- C# 多线程操作样例
- ueditor:原谅我这一生不羁放纵爱独特
- 【转】C++中继承中的同名成员问题
- IbatisNet开发使用小结
- hdu 4602 Partition (概率方法)
- 关于cocopads 不能正确安装的问题
- HTML基础加强
- python转义符
- 【读书笔记】Cronjob原理及源码分析
- Nginx-rtmp 直播媒体实时流实现
- 利用MVC Chart 打造后台图表、前端图表
- ZH奶酪:PHP 使用DOMDocument操作XML
- HttpURLConnection如何添加请求头?
- 查看是否安装.NET Framework、.NET Framework的版本号、CLR版本号
- 17、配置嵌入式servlet容器(1)
- Intermediate_JVM 20180306 : 运行时数据区域