python中的for循环
在控制台打印你好世界 10遍,i可以随便命名,写你能记得住的名称就行。
# for i in range(10):
# print("你好,世界!")#rang(起始值4,结束值10-不包含,步长-默认1) 这里步长设置2
for i in range(4,10,2):
print(i)
小案例1
#【1:11】,从2开始到10循环次数,1起始数字不包含,11结尾数字不包含。:
for i in range(1,11):
print("第",i,"次打印:你好,世界!")
#小案例2:
for i in range(10):
print("第",i,"次打印:你好,世界!")
#小案例1,和小案例2,输出结果是一样的,# 循环中断
# for i in range(1,11):
# if i==5:
# print("第5年,申请了提前还款,今年不用还了!")
# continue #结束当前循环
# if i==6:
# print("第", i, "年,还款24万元!")
# continue
# if i==8:
# print("第", i, "年,提前还清所有贷款!")
# break #终止整个循环
# print("第",i,"年,还款12万元!")#无限循环
i=1
while True:
print("第",i,"次打印:你好,世界!")
i=i+1【练习】:求和和还款问题。
# #1-100之间所有整数之和
# num=0
# for i in range(1,101):
# num=num+i
# print(num)
#还款
totalMoney=0 #累计还款金额
for i in range(1,11):
totalMoney=totalMoney+12
print("第",i,"年,还款12万元!累计已还",totalMoney,"万!,还差",120-totalMoney,"万!")
print("---已还清",totalMoney,"万元!")【练习】利用for循环遍历各种容器(列表,元组,字典,集合等。)
names=["张三","李四","王五","赵六"]
# #直接遍历
# for name in names:
# print(name)
# #构造索引
# for i in range(0,len(names)):
# print(names[i])
#遍历元组
scores=(67,78,68,87,92,45,69,77)
# for i in range(0,len(scores)):
# print(scores[i])
# #平均分
# total=0
# for score in scores:
# total=total+score
# print(total/len(scores))
# #遍历字典 只获取键
# dictA={"name":"张三","age":18,"hobby":"打球"}
# for x in dictA:
# print(x,dictA[x])
#遍历集合
setA={1,324,243,535,23}
for i in setA:
print(i)#for循环和if判断语句组合【for循环只循环一遍,元素里的东西】
#判断某个名字是否存在
names=["张三","李四","王五","赵六"]
key=input("请输入要查询的姓名:")
result="不存在" #保存结果
for name in names:
if name==key:
result="存在"
print(result)
#计算及格率
scores=(67,78,68,87,92,45,69,77,53,89)
count=0
for score in scores:
if score>=60:
count=count+1
print(count/len(scores))
#苹果打8折,其他商品不打折,求购物车总价
cart = {"apple": 25, "banana": 12, "orange": 9}
totalPrice=0
for key in cart:
name=key
price=cart[key]
if name=="apple":
price=price*0.8
totalPrice=totalPrice+price
print("购物车总价为:",totalPrice)求最大值最小值
scores=[67,78,68,87,92,45,69,77]
#最高分和最低分
# maxScore=scores[0]
# minScore=scores[0]
# for score in scores:
# if score>maxScore:
# maxScore=score #将更大的当前值更新为最大值
# if scorelongest:
longest=l
result=s
print("最长字符串:",result,"长度:",longest)