【Python】Learn Python the hard way, ex4 使用变量

cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven


print "There are", cars, "cars available."
print "There are only", drivers, "drivers availabe."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."

'''
Test Results:
There are 100 cars available.
There are only 30 drivers availabe.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 to carpool today.
We need to put about 3 in each car.
'''


心得:

1,想起了当年学习C++时,一个有意义的变量名的事情

2,一次全敲对也不容易


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用python进行成绩转换可以采用以下步骤: 1. 使用random函数生成20个随机成绩,并将其存入txt文本文件ex4_scores.txt中。 2. 使用循环语句逐个读取成绩并进行等级转换,将成绩和等级存入txt文本文件ex4_degrees.txt中,并在屏幕上输出成绩和等级。 具体实现步骤如下: 1. 导入random模块,并创建一个空的成绩列表s_list。 2. 使用for循环生成20个随机成绩,并将其添加到s_list中。 3. 打开ex4_scores.txt文件,并以写入模式打开文件对象f。 4. 使用循环语句逐个将成绩写入文件中,每个成绩占一行。 5. 关闭文件对象f。 6. 打开ex4_scores.txt文件,并以读取模式打开文件对象f。 7. 使用readlines函数将文件中的成绩读取为一个列表score_list。 8. 创建一个空的等级列表d_list,并定义等级对应关系为'DCBAAE'。 9. 使用for循环遍历score_list中的每个成绩,根据成绩进行等级转换,并将等级添加到d_list中。 10. 使用for循环遍历s_list和d_list,将成绩和对应的等级分别输出到屏幕上。 11. 打开ex4_degrees.txt文件,并以写入模式打开文件对象f。 12. 使用writelines函数将s_list和d_list分别写入文件中,每个列表占一行。 13. 关闭文件对象f。 请注意,为了避免混淆,上述代码中的文件操作部分与原文中的代码稍作修改。 代码实现如下所示: ```python import random # 生成20个随机成绩 s_list = [] for i in range(20): s_list.append(random.randint(0, 101)) # 将成绩写入ex4_scores.txt文件 with open('ex4_scores.txt', 'w') as f: for s in s_list: f.write(str(s)) f.write('\n') # 从ex4_scores.txt文件中读取成绩,进行等级转换并输出 degrees = 'DCBAAE' d_list = [] with open('ex4_scores.txt', 'r') as f: score_list = f.readlines() for n in score_list: if int(n) >= 60: d_list.append(degrees[(int(n) - 60) // 10]) else: d_list.append(degrees[-1]) for e in range(20): print('{}分为:{}'.format(s_list[e], d_list[e])) # 将结果存入ex4_degrees.txt文件 with open('ex4_degrees.txt', 'w') as f: f.write(str(s_list) + '\n') f.write(str(d_list) + '\n') ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值