Exercise 20: Functions and files
Recall the main points of the function, and then do this exercise while noticing how the functions and files work together.
1 fromSysImportargv2 3Script, Input_file =argv4 5 defPrint_all (f):6 PrintF.read ()7 8 defRewind (f):9 f.seek (0)Ten One defPrint_a_line (Line_Count, f): A PrintLine_Count, F.readline () - -Current_file =Open (input_file) the - Print "First let ' s print the whole file:\n" - - Print_all (current_file) + - Print "Now let's rewind, kind of like a tape." + A Rewind (Current_file) at - Print "Let ' s print three lines:" - -Current_line = 1 - print_a_line (Current_line, Current_file) - inCurrent_line = current_line + 1 - print_a_line (Current_line, Current_file) to +Current_line = current_line + 1 -Print_a_line (Current_line, Current_file)
View Code
Pay special attention to how we pass the current line number information each time we run print_a_line .
The results you should see
Bonus points Exercise
- Read through the script and add annotations before each line to understand what's going on in the script.
- Each time Print_a_line runs, you pass a variable called current_line . Each time the function is called, the current_line is printed out to track how it becomes line_count in the print_a_line .
- Find out where each function is used in the script. Check the def line to verify that the parameter is not used correctly.
- Go online and study what the seek function in file does. Try running pydoc file to see if you can learn more.
- Consider the function of the shorthand operator of + = , write a script, and use this operator to try it out.
Exercise Exercises
1.
Stupid way to learn Python (20)