python学习第六天

习题19 函数和变量

def cheese_and_crackers(cheese_count,boxes_of_crackers):       #定义一个函数和这个函数需要的参数个数
    print(f"you have {cheese_count} cheese")
    print(f"you have {boxes_of_crackers} boxes of crackers!")
    print("man that's enough for a party" )
    print("get a blanket.\n")


print("we can just give the function numbers directly")
cheese_and_crackers(20,30)                                       #调用函数参数为20 30

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

cheese_and_crackers(amount_of_cheese, amount_of_crackers)           #调用函数,参数为10和50

print("we can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)                                  #调用函数,参数为30 11

print("and we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)  #调用函数,参数在第二次调用的基础上再进行变化

此习题主要学写了函数的构建和调用,函数调用的参数必须是事先定义好的变量或者数字,加强对函数的认识

习题20 函数和文件

from sys import argv

script, input_file = argv

def print_all(f):
    print(">>>f=",repr(f))
    print(f.read())

def rewind(f):
    f.seek(0)                           #seek()函数移动文件读取指针到指定位置

def print_a_line(line_count, f):
    print(line_count, f.readline())   """readline()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存;readlines()
                                         一次性读取整个文件;自动将文件内容分析成一个行的列表,read()读取整个文件,将文件内容
                                         放到一个字符串变量中"""

current_file = open(input_file)

print("first let's print the wwhole file:\n")

print_all(current_file)                  #调用print_all函数,

print("now let's rewind, kind of like a tape.")

rewind(current_file)                     #调用rewind函数

print("let's print three lines:")

current_line = 1
print_a_line(current_line, current_file)  #调用print_a_line函数,输出每一行的内容

current_line += 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

此习题要注意seek()函数和readline()函数的用法,以及编码形式错误的改正方法,以及更加
熟练的创造和运用函数,注意区分read(),readline(),readlines()的用法区别,seek()函数的处理对象是字节不是行,所以seek(0)只是转到文件的0字节处(就是第一个字节的地方)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值