Lecture 1



CSC 241 NotesYosef MendelsohnWith many thanks to Dr. Amber Settle for the original version of these notes.Prof Settle's notes in turn are based on the Perkovic text.ModulesA module in Python is simply a file that contains Python code.For example, the ‘.py’ files you’ve been writing for your last couple of labs / assignments are modules.The purpose of "modules" is no different from the idea of developing and storing programs in a file: namely code reuse. Modules provide a way to organize the components (i.e. smaller pices) that make up larger software programs. Let's look at the 'math' module that is built in to Python. A built-in (or predefined) module is one that is automatically installed when you install Python. The typically installation of Python includes many such built-in modules. For example, all installations of Python will include the ‘math’ module. The math moduleThe core Python language (i.e. without even requiring the math module) supports basic mathematical operators.Those include:Comparison operators: <, <=, >, >=, ==, !=Algebraic operators: +, -, *, /For other mathematical operators, such as the square root function, trigonometric functions, and many others, we can use the math module. This module is a library of mathematical functions, as well as some well-known constants (e.g. PI).In order to use the math module, the module must be explicitly imported into the current "execution environment" where you are programming. If we neglect to import a module, and try to use one of the functions inside that module, we get an error. For example, here we try to invoke the sqrt() function, but without having first imported the math module:>>> sqrt(3)Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> sqrt(3)NameError: name 'sqrt' is not definedA module is imported using the import statement with the general format:import <name of module>Unfortunately just importing the module isn’t always sufficient, as the following example illustrates:>>> import math>>> sqrt(3)Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> sqrt(3)NameError: name 'sqrt' is not definedThe square root function is defined in the math module, but the execution environment isn’t aware of this. We must explicitly tell the program where (i.e. in which module) this 'sqrt' function can be found:>>> math.sqrt(3)1.7320508075688772Other functions: The math module includes all kinds of other functions such as exp (for exponents), log (for logarithms), cos (for cosine), fabs (for absolute value), etc, etc. Constants: In addition to all kinds of mathematical functions, the math module also defines two well-known constants, 'pi', and 'e'. As with the functions, we must notify our program that these constants are contained inside the math module.>>> print(math.pi)3.141592653589793>>> print(math.e)2.718281828459045To summarize, the math module is just a file containing a bunch of functions and constants. As shown above, the module is imported using an import statement which allows us to access the functions defined in the module, although we must use the name of the module in front of the function and constant names.Do a web search to find the API for Python’s math module. Experiment with some of the functions and constants. File processing (I/O)Much of computing involves the processing of data stored in files.A file is a sequence of data stored on a secondary memory device such as the hard drive on a computer, a USB drive, magnetic tape storage, etc.A text file contains a sequence of characters. You can think of a text file as one very, very long string. One important thing to be aware of when working with text files, is that every new line (e.g. for example, every time the user typing the file pressed ‘enter’) is separated from the next line by the special character \n . Note: This newline character does not apply to text editors where word-wrap is turned on. It only applies to actual new lines in the file.Processing a file includes the following:Opening a file for reading (or writing)Reading from the file and (or writing to the file)Closing the fileWhy is it necessary to explicitly open and close files? The short answer is that the operating system needs to manage files so that they remain consistent. One very important part of this is making sure that two programs aren’t working on the same file at the same time. Imagine if two programs were wrting information to the same file at the same time. This would almost certainly cause the file to have wildly inconsistent data. Forcing programs to explicitly open and close files allows the operating system to ensure that such conflicts can not occur – or at least to force us to resolve these conflicts so that we don’t corrupt the data contained in the files.Reading a fileLet's open a file called example.txt for reading. That is, we are only planning on reading information from the file. We are not planning on outputting text to the file (yet). The second argument, 'r', is what tells our program that we are only going to be reading from the file. infile = open(‘example.txt’, ‘r’)The variable infile is very important. It is our reference to the opened file. That is, rather than refer to the file by its filename, we will refer to it by this reference. This is typical in programming. Common identifiers for a file reference of files we are reading from include: fin, in_file, inputFile, etc, etc. For output files we often use: fout, outfile, etcThere are three methods commonly used to read from a file: read()readline()readlines()Note that we need to use our reference (e.g. ‘infile’) in order to invoke these methods:infile.read(): Returns a single string containing all of the remaining (i.e. unread) contents of the file. Example: If you invoke this method immediately after opening a file, then you will get back the entire file as one very long string. If you invoke when the cursor (discussed shortly) is halfway through the file, you will get all fo the remainder of that file.infile.readline(): Returns the next line of the file i.e. the text up to and including the newline character ‘\n’. Example: If you invoke this method imediately after opening a file, you will get back the very first line of the file. infile.readlines(): Returns a list whose items are the remaining, unread lines of the file. To close a file associated with the variable infile, you write:infile.close()Note: You should always close a.ny file once you are done using it. The helps prevent the possibility of corrupting the file. Examples: There are four functions all called sample() (with nuumbers 1 through 4) in the file file_functions.py . All four do the same thing – open a file for reading and then read and output the content of the file.Let’s consider each function as run on the file example.txt.Here are some additional practice problems:I may demonstrate some of these in class. However, you should be sure to work on replicating these functions on your own before looking at the answer. Write a function called numLines() that takes one input argument, a file name, and returns the number of lines in the corresponding file.It would be used as follows:>>> numLines(‘example.txt’)4Write a function called numChars() that takes one input argument, a file name, and returns the number of characters in the file.It would be used as follows:>>>numChars('example.txt')89Write a function called stringCount() that takes 2 string inputs, a file name and a target string, and returns the number of occurrences of the target string in the file.It would be used as follows'>>>stringCount('example.txt’, 'line')5Hint: There is a string function that lets you count the number of times a substring appears in a string.Try the above, but search for the string ‘is’. What do you notice? How might you fix this?See this week’s examples file for the solutions.Writing to a fileTo write to a file, the file must be opened, but this time, for writing. We indicate this with the 'w ' argument as shown here:>>> outfile = open('out.txt', 'w')How does this work?If there is no file out.txt in the current working directory, the above open() function will create it. If a file out.txt exists, then any content that was previously inside that file will be truncated (erased)! In other words, you’ll want to be careful here! If your file has some important stuff in it, then you will completely blow away all of that “old” content! For example:outfile = open('phd_thesis.txt','w')#oops...The ‘cursor’ When you first open a file (whether reading or writing), Python places an invisible pointer in the file called the "cursor". This invisible pointer keeps track of where you are in the file. Not surprisingly, when you first open a file, the cursor is placed at the very beginning of the file. If, for example, you read a single line of the file, then after that command has been executed, the cursor will be placed at the beginning of the second line. Once a file is opened for writing, the write() function can be used to write strings to it.The write() function will write the string at the cursor position. Recall that when you first open a file, the cursor (that sort of 'invisible pointer') is always placed at the very beginning of that file. >>> outfile.write('This is the first line. ')23Question: What’s up the the “23” above?Answer: The write() function, in additiion to writing the information to the file, also returns the number of characters that was written. Since the previous example was demonstrated using the interactive console, we see the value returned by the function is outputted to the screen. This is a very good example of how some functions return a value – that you may not need to use. That is, the write() function is used mainly for outputting information to the stream. However, the function also gives you a little something extra in terms of the returned length “just to be nice”! We don’t have to use it, it’s just there for possible convenience. Back to the cursor: After you invoke commands to write to a file, the cursor will move. After the above command, the cursor will now point to the position after the period. The next write command will execute starting at that position.>>> outfile.write(' Still the first line ... \n')28Everything written up until the new line character \n is written to the same line. The ‘\n’ character: What if you want to begin a new line? Recall that there is a special character that refers to a newline: \n Writing this character to the file creates a new line. So if you write in a \n character, anything that follows will go to the next line. Okay, since we included the \n character in the previous line. Anything we write now will go on the following line. >>> outfile.write('Now we are in the second line.\n')31Another useful character is \t. This character writes a tab.Note: The write() function only writes strings. To write to a file content that is a data type that is not a string, we must first convert that content to a string. For example, what if we simply wanted to output the number 5? Answer: Recall that we can convert floats and integers to strings with the str() function.>>> outfile.write('Outputting a 5: ' + str(5) + '\n')50Here is where the string format() function is helpful. For example, we can print an exact copy of the previous line using the format() function:>>> outfile.write('Non string values like {0} must be converted first.\n'.format(5))50Important: Recall that if you open a file to write, and that file currently exists, all of the information in that file willl be erased! So, if we want to write to an output file without removing the existing contents, we must open the file in a different way:>>> outfile = open('out.txt', 'a')This will open the output file out.txt and append new information to the end of the file.Any information already in the file will not be altered. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download