python-for循环代码练习题

时间:2025-09-20 07:54:50  阅读量:  分类:标签:
#还款
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])
# #平班级均分数
scores=(67,78,68,87,92,45,69,77)
# 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)
# #判断某个名字是否存在
# 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]
print(min(scores)) #获取最小值
print(max(scores)) #获取最大值
#获取最长字符串
strings=["hello","world","你好世界","你是谁?","who are you?"]
longest=len(strings[0])
result=""
for s in strings:
    l=len(s)
    if l>longest:
        longest=l
        result=s
print("最长字符串:",result,"长度:",longest)