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.点击

你可能感兴趣的:(exercise 19)