exercise 19

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print(f"You have {cheese_count} cheeses!")
    print(f"You have {boxes_of_crackers} boxes of crackers!")
    print("Man that's enough for a parth!")
    print("Get a blanket.\n")


print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)


print("OR, we can use bariables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese, amount_of_crackers)


print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)


print("And we can combine the two, variables and math:")
# 调用cheese_and_crackers函数
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers+ 1000)

练习

  1. 倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。
  2. 从最后一行开始,倒着阅读每一行,读出所有的重要字符来。
  3. 自己编至少一个函数出来,然后用10种方法运行这个函数。

答案

from sys import argv

script, input_file = argv

# 定义print_all函数
def print_all(f):
    # 打印文件全部内容
    print(f.read())

# 定义函数rewind,参数f引用文件对象
def rewind(f):
    # f。seek(0)是让基准点回到开始位置
    # 如果是seek(1),那就是让基准点回到当前位置
    # 如果是seek(2),那就是让基准点回到结束为止
    f.seek(0)

# 定义函数print_a_line,参数line_count和f都是引用文件对象的
def print_a_line(line_count, f):
    #f.readline()是一行一行读取的
    print(line_count, f.readline())

#  把文件input_file对象赋值给current_file
current_file = open(input_file)

# 打印
print("First let's print the whole file:\n")

# 调用函数print_all
print_all(current_file)

# 打印
print("Now let's rewind, kind of like a tape.")

# 调用函数rewind,作用就和倒带差不多
rewind(current_file)

# 打印
print("Let's print three lines:")

# 把1赋值给current_line
current_line = 1
# 调用函数print_a_line
print_a_line(current_line, current_file)

# current_line自增
current_line = current_line + 1
# 调用print_a_line函数
print_a_line(current_line, current_file)

# 自增
current_line = current_line + 1
# 调用函数print_a_line
print_a_line(current_line, current_file)

第一次print_a_line被调用, current_line被赋值1
第二次print_a_line被调用, current_line被赋值2
第三次print_a_line被调用, current_line被赋值3

4.点击
5.点击

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 这篇文章是手册的中文译版整理而来(英文看着太慢了,感谢前人铺路Orz...),vim的markdown插件和实时预...
    Himryang阅读 12,035评论 0 20
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,906评论 0 4
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,241评论 25 709
  • 春天来了,很多病毒在空气中蔓延,生病的也就多了,很多人抱怨是自己体质差所以容易得病。就我看来,只要你愿意,体质完全...
    跟着宝宝一起成长阅读 2,806评论 0 4
  • 富爸爸说:“世界上到处都是有伟大创意的人,但是因此获得巨额财富的人屈指可数。究其原因,是因为在这个世界上,拥有企业...
    Fei向宇宙阅读 3,514评论 0 1

友情链接更多精彩内容