learn python the hard way (personal) -- Ex18-

Ex18:

Introducing the function

Study Drills

Create a function checklist for later exercises. Write these checks on an index card and keep it by you while you complete the rest of these exercises or until you feel you do not need the index card anymore:

  1. Did you start your function definition with def?
  2. Does your function name have only characters and _ (underscore) characters?
  3. Did you put an open parenthesis ( right after the function name?
  4. Did you put your arguments after the parenthesis ( separated by commas?
  5. Did you make each argument unique (meaning no duplicated names)?
  6. Did you put a close parenthesis and a colon ): after the arguments?
  7. Did you indent all lines of code you want in the function four spaces? No more, no less.
  8. Did you "end" your function by going back to writing with no indent (dedenting we call it)?

When you run ("use" or "call") a function, check these things:

  1. Did you call/use/run this function by typing its name?
  2. Did you put the ( character after the name to run it?
  3. Did you put the values you want into the parenthesis separated by commas?
  4. Did you end the function call with a ) character?

Use these two checklists on the remaining lessons until you do not need them anymore.

Ex19:

Running a function in different ways.

Ex20:

functions and files

from sys import argv

scrip, input_file = argv

def print_all(f):
    print(f.read())

def rewind(f):
    f.seek(0)

def print_a_line(line_count,f):
    print(line_count,f.readline())

current_file = open(input_file)

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

print_all(current_file)

#Is the rewind necessary?
print("Now let's rewind, kind of like a tape.")

rewind(current_file)

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

current_line = 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

注意seek 和 readline

Each time you do f.seek(0) you're moving to the start of the file. Each time you do f.readline() you're reading a line from the file and moving the read head to right after the \n that ends that line. 

Why are there empty lines between the lines in the file?

The readline() function returns the \n that's in the file at the end of that line. Add a end = "" at the end of your print function calls to avoid adding double \n to every line.

 

Ex21:

 a new Python word return to set variables to be a value from a function

def add(a,b):
    print(f"ADDING {a} + {b}")
    return a + b

 

Ex22:

复习、总结之前学的内容。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值