print(程序结束)_Head First Programming第5章for循环与print()和close()逻辑关系

《Head First Programming》深入浅出程序设计 第5章

for循环与 文件close()和print()打印输出 的关系梳理

例题一:

文件results.txt中保存这些数据:

Johnny 8.65
Juan 9.12
Joseph 8.45
Stacey 7.81
Aideen 8.05
Zack 7.21
Aaron 8.31

需要:找到最高成绩,并打印输出。

涉及知识点包括:

1.open()函数:打开文件并且,赋值给文件句柄:result_f 。

2.for循环:for line in result_f 把文件中,每一行line进行迭代循环,找出最高分highest_score 。

3.多重赋值:(name,score) = line.split()

4.split()方法分割字符串 (name,score) = line.split()

5.文件close()和print()打印输出

写的时候,发现文件close()和print()顺序改变,输出成绩不一样,梳理一下:

5faa60dd891f9eb84ae19f8f9056858a.png

第一段代码,先关闭文件result_f.close(),然后进行print()输出,可以得到最高成绩 9.12。

highest_score = 0
result_f = open("results.txt")
for line in result_f:
    (name,score) = line.split()
    if float(score) > highest_score:
        highest_score = float(score)
result_f.close()
print(highest_score)

第二段代码,先print()输出,然后关闭文件result_f.close(),得到两个成绩 8.65 和 9.12。

highest_score = 0
result_f = open("results.txt")
for line in result_f:
    (name,score) = line.split()
    if float(score) > highest_score:
        highest_score = float(score)
        print(highest
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值