CSE 160 Section 03 Code Examples 1. An example of opening a file and printing all of its contents: input = open("input.txt", "r") for line in input: print line, input.close() The comma at the end of the print statement stops python from printing a redundant \n in addition to the one that is already in the line variable. 2. An example of opening a file and counting the amount of lines it contains: input = open("input.txt", "r") line_number = 0 for line in input: line_number = line_number + 1 input.close() print line_number 3. An example of opening a file and only printing the odd numbered lines (where the first line is 1): input = open("input.txt", "r") line_number = 0 for line in input: if line_number % 2 == 0: print line, line_number = line_number + 1 input.close() 4. An example of opening a file and writing to it: output_file = open("output.txt", "w") output_file.write("apple\n") output_file.write("banana\n") output_file.write("nyan\n") output_file.close() 5. An example of some basic uses of a list: data = [] data.append(39) data.append(9001) data.append(42) # data = [39, 9001, 42] at this point data.sort() # data = [39, 42, 9001] at this point # Report the amount of entries in the list, which is 3 print len(data) # Prints each value in the list for entry in data: print entry # An alternative way to print each value in the list for i in range(len(data)): print data[i] 6. An example of a function definition: # Returns the sum of the three given arguments def example_function(a, b, c): return a + b + c 7. An example of rstrip(): example_string = "A string with a newline at the end\n" stripped_string = example.rstrip() # The contents of the two variables: # example_string = "A string with a newline at the end\n" # stripped_string = "A string with a newline at the end" 8. An example of String formatting: a = "%s => %d, %f" % ("Example String", 42, 9001.0) print a # Example String => 42, 9001