This shows you the differences between the selected revision and the current version of the page.
| core:part9_answers 2010/03/20 15:16 | core:part9_answers 2010/04/18 08:00 current | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | =====9-1===== | ||
| + | <code python> | ||
| + | #!/usr/bin/python3 | ||
| + | # | ||
| + | # 9-1. File Filtering. | ||
| + | # Author: PolyMath | ||
| + | # | ||
| + | def main(): | ||
| + | text_file = open('test.txt') | ||
| + | lines = [line for line in text_file if line[0] != '#'] # dicard lines beginning with '#' | ||
| + | for line in lines: | ||
| + | if '#' in line: | ||
| + | idx = line.find('#') # locate any other '#' | ||
| + | print(line[:idx]) # don't print the text after the '#' | ||
| + | else: | ||
| + | print(line.rstrip()) # here if no '#' found in the line of text. | ||
| + | print('\nDone!') | ||
| + | # | ||
| + | # Call the main function. | ||
| + | if __name__ == "__main__": | ||
| + | main() | ||
| + | </code> | ||
| + | |||
| + | =====9-2===== | ||
| + | <code python> | ||
| + | #!/usr/bin/python3 | ||
| + | # | ||
| + | # 9-1. File Filtering. | ||
| + | # Author: PolyMath | ||
| + | # | ||
| + | def main(): | ||
| + | while True: | ||
| + | fname = input("Enter the name of the file here: ") | ||
| + | line_num = int(input("and the number of lines to display < 40: ")) | ||
| + | try: | ||
| + | text_file = open(fname) | ||
| + | if line_num > 40: | ||
| + | continue # try again | ||
| + | for count in range(line_num + 1): | ||
| + | line = text_file.readline().rstrip() # get a line of text. | ||
| + | print(line) | ||
| + | except IOError: # open file error. | ||
| + | print("The name of the file is 'test.txt'. try again.\n") | ||
| + | break | ||
| + | print('\nDone!') | ||
| + | # | ||
| + | # Call the main function. | ||
| + | if __name__ == "__main__": | ||
| + | main() | ||
| + | </code> | ||
| + | |||
| + | =====9-4===== | ||
| + | <code python> | ||
| + | #!/usr/bin/python3 | ||
| + | # | ||
| + | # 9-1. File Filtering. | ||
| + | # Author: PolyMath | ||
| + | # | ||
| + | import sys | ||
| + | # | ||
| + | def bye(): | ||
| + | print('\nDone!') | ||
| + | sys.exit() | ||
| + | # | ||
| + | def main(): | ||
| + | while True: | ||
| + | fname = input("\nEnter the name ('readme.txt') of the file here: ") | ||
| + | try: | ||
| + | text_file = open(fname) | ||
| + | lines = [line.rstrip() for line in text_file] # load all the file into memory. | ||
| + | limit = len(lines) | ||
| + | char = input("Press a key to continue 'q' to quit.") | ||
| + | if char == 'q': | ||
| + | bye() | ||
| + | for line_num in range(limit): | ||
| + | print(lines[line_num]) | ||
| + | |||
| + | |||
| + | |||
| + | except IOError: # open file error. | ||
| + | print("The name of the file is 'readme.txt'. try again.\n") | ||
| + | bye() | ||
| + | |||
| + | # | ||
| + | # Call the main function. | ||
| + | if __name__ == "__main__": | ||
| + | main() | ||
| + | </code> | ||
| + | |||
| + | =====9-5===== | ||
| + | <code python> | ||
| + | #!/usr/bin/python3 | ||
| + | # | ||
| + | # 9-5. Test Scores | ||
| + | # Author: PolyMath | ||
| + | # | ||
| + | def get_grade(score): | ||
| + | if score > 89: | ||
| + | return 'A' | ||
| + | elif score > 79: | ||
| + | return 'B' | ||
| + | elif score > 69: | ||
| + | return 'C' | ||
| + | elif score > 69: | ||
| + | return 'D' | ||
| + | else: | ||
| + | return 'E' | ||
| + | # | ||
| + | def main(): | ||
| + | while True: | ||
| + | reply = input("\nInput Scores data from a file y/n. ") | ||
| + | if reply == 'y': | ||
| + | fname = input("Enter the file name here: ") # get the filename | ||
| + | try: | ||
| + | fobj = open(fname, 'r') # open the file for reading. | ||
| + | line = fobj.readline() # get the file contents. | ||
| + | line = line.rstrip() | ||
| + | scorelist = line.split(',') | ||
| + | except IOError: | ||
| + | print("\nThe filname ", fname, "does not exist.") | ||
| + | continue | ||
| + | else: | ||
| + | print('\nEnter all the scores (1 - 100) for the exam as a') | ||
| + | reply = input('comma-seperated list E.G. 65,87,34,... ') | ||
| + | if reply == '': | ||
| + | break | ||
| + | scorelist = reply.split(',') | ||
| + | # if score is a string digit, convert it to an integer and add it to scores list. | ||
| + | scores = [int(score) for score in scorelist if score.isdigit() and int(score) < 101] | ||
| + | # if the list of integers != list of strings entered, then error. | ||
| + | if len(scores) != len(scorelist): | ||
| + | print('\nTher has been an error. Try again.') | ||
| + | print("This is the list that was input:",scorelist) | ||
| + | continue | ||
| + | for score in scores: | ||
| + | print("An exam score of '{0}' is a grade '{1}'".format(score,get_grade(score))) | ||
| + | average = float(sum(scores))/len(scores) | ||
| + | print("The average score is: {0:.2f}".format(average)) | ||
| + | print('Done!') | ||
| + | # | ||
| + | # Call the main function. | ||
| + | main() | ||
| + | </code> | ||
| + | |||
| + | =====9-6===== | ||
| + | <code python> | ||
| + | #!/usr/bin/python3 | ||
| + | # | ||
| + | # 9-6. File Comparison. | ||
| + | # Author: PolyMath | ||
| + | # | ||
| + | def main(): | ||
| + | fname1 = 'readme1.txt' | ||
| + | fname2 = 'readme2.txt' | ||
| + | fobj1 = open(fname1, 'r') | ||
| + | fobj2 = open(fname2, 'r') | ||
| + | line1 = fobj1.readline() # get the first line from the file | ||
| + | line2 = fobj2.readline() | ||
| + | line_number = 0 # initialize line count | ||
| + | while line1 == line2: | ||
| + | line1 = fobj1.readline() # get the next line from the file | ||
| + | if not line1: | ||
| + | break | ||
| + | line2 = fobj2.readline() # get the next line from the file | ||
| + | if not line2: | ||
| + | break | ||
| + | line_number += 1 | ||
| + | col_number = 0 # initialize column count. | ||
| + | while line1[col_number] == line2[col_number]: # are the 2 lines equal. | ||
| + | col_number += 1 # yes. increment count and try again. | ||
| + | print("The two files differ on line: '{0}' and column '{1}'".format(line_number + 1, col_number + 1)) | ||
| + | print("\nDone.") | ||
| + | # | ||
| + | # Call the main function. | ||
| + | if __name__ == "__main__": | ||
| + | main() | ||
| + | </code> | ||
| + | |||
| + | =====9-13-1===== | ||
| + | 9-13-1. Command-Line Arguments. | ||
| + | "Command-line arguments are those arguments given to the program in addition | ||
| + | to the script name on invocation." | ||
| + | |||
| + | "Are command-line arguments useful? Commands on Unix-based systems are typically | ||
| + | programs that take input, perform some function, and send output as a stream of | ||
| + | data. These data are usually sent as input directly to the next program, which | ||
| + | does some other type of function or calculation and sends the new output to | ||
| + | another program, and so on. Rather than saving the output of each program and | ||
| + | potentially taking up a good amount of disk space, the output is usually | ||
| + | "piped" into the next program as its input." | ||
| + | |||
| + | =====9-13-2===== | ||
| + | <code python> | ||
| + | #!/usr/bin/python3 | ||
| + | # | ||
| + | # 9-13 Command-Line Arguments. | ||
| + | # Author: PolyMath | ||
| + | # | ||
| + | import sys | ||
| + | # | ||
| + | def main(): | ||
| + | print("you entered the following command-line arguments: ", str(sys.argv[1:])) | ||
| + | print('\nDone!') | ||
| + | # | ||
| + | # Call the main function. | ||
| + | if __name__ == "__main__": | ||
| + | main() | ||
| + | </code> | ||
| + | |||
| + | =====9-14===== | ||
| + | <code python> | ||
| + | #!/usr/bin/python3 | ||
| + | # | ||
| + | # 9-14. caculator | ||
| + | # Author: PolyMath | ||
| + | # | ||
| + | import sys | ||
| + | from operator import add, sub, mul, mod,truediv, pow | ||
| + | nums = [None, None] | ||
| + | # | ||
| + | def bye(): | ||
| + | print('Done!\n') | ||
| + | sys.exit() | ||
| + | # | ||
| + | def main(): | ||
| + | operators = {'+':add, '-':sub, '%':mod, '*':mul, '/':truediv, '^':pow} | ||
| + | expr = (sys.argv[1:]) # get the expression | ||
| + | operator = expr[1] | ||
| + | if operator not in operators: # is the operator legal | ||
| + | print("Wrong operator used. use one from (+, -, *, /, %, ^)\n") | ||
| + | bye() # no, then quit. | ||
| + | try: | ||
| + | nums[0] = float(expr[0]) # are the operands numbers | ||
| + | nums[1] = float(expr[2]) | ||
| + | except ValueError: # no, then quit | ||
| + | print("\nThere has been an error. Enter two numbers EG. '2 + 5'.") | ||
| + | bye() | ||
| + | solution = operators[operator](*nums) # do the arithmetic | ||
| + | print("{0} {1} {2} = {3}".format(nums[0], operator, nums[1], solution)) | ||
| + | bye() | ||
| + | # | ||
| + | # Call the main function. | ||
| + | main() | ||
| + | </code> | ||
| + | |||
| + | =====9-15===== | ||
| + | <code python> | ||
| + | #!/usr/bin/python3 | ||
| + | # | ||
| + | # 9-15. Copying Files. | ||
| + | # Author: PolyMath | ||
| + | # | ||
| + | import sys | ||
| + | # | ||
| + | def main(): | ||
| + | fname1 = sys.argv [1] | ||
| + | fname2 = sys.argv [2] | ||
| + | file1 = open(fname1, 'r') | ||
| + | file2 = open(fname2, 'w') | ||
| + | lines = file1.readlines() | ||
| + | file2.writelines(lines) | ||
| + | print("\nSucces! Copied file '{0}' to file '{1}'.".format(fname1, fname2)) | ||
| + | print('\nDone!') | ||
| + | # | ||
| + | # Call the main function. | ||
| + | if __name__ == "__main__": | ||
| + | main() | ||
| + | </code> | ||
| + | |||
| =====9-10===== | =====9-10===== | ||
| ====main program==== | ====main program==== | ||