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:
- Did you start your function definition with def?
- Does your function name have only characters and _ (underscore) characters?
- Did you put an open parenthesis ( right after the function name?
- Did you put your arguments after the parenthesis ( separated by commas?
- Did you make each argument unique (meaning no duplicated names)?
- Did you put a close parenthesis and a colon ): after the arguments?
- Did you indent all lines of code you want in the function four spaces? No more, no less.
- 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:
- Did you call/use/run this function by typing its name?
- Did you put the ( character after the name to run it?
- Did you put the values you want into the parenthesis separated by commas?
- 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:
复习、总结之前学的内容。