<jupyter_start><jupyter_text>DSO109 Python : Lesson Seven Companion Notebook  Table of Contents * [Table of Contents](DS109L7_toc)    * [Page 1 - Standard Library Intro](DS109L7_page_1)    * [Page 2 - Standard Library](DS109L7_page_2)    * [Page 3 - Modules](DS109L7_page_3)    * [Page 4 - Python Standard Modules](DS109L7_page_4)    * [Page 5 - The **math** Module](DS109L7_page_5)    * [Page 6 - Modules Activity](DS109L7_page_6)    * [Page 7 - **pip** Packages](DS109L7_page_7)    * [Page 8 - Accessing and Modifying Files](DS109L7_page_8)    * [Page 9 - Reading From And Writing To Files](DS109L7_page_9)    * [Page 10 - Updating File Strings](DS109L7_page_10)    * [Page 11 - Lesson 7 Practice Hands-On](DS109L7_page_11)    * [Page 12 - Lesson 7 Practice Hands-On Solution](DS109L7_page_12)      Page 1 - Standard Library Intro[Back to Top](DS109L7_toc)<jupyter_code>from IPython.display import VimeoVideo
# Tutorial Video Name: Standard Library
VimeoVideo('238447925', width=720, height=480)<jupyter_output><empty_output><jupyter_text>Standard Library IntroThus far, you have learned about the fundamentals of programming in Python, and you've seen and used several data types and keywords that are built into the language. Python also has a _standard library_, that has an extensive range of built-in modules that provide access to system functionality. In this lesson, you will learn about Python's standard library and a few of the more widely-used Python packages that are built and shared by third-party developers.--- Setup1. First, open up your command prompt/terminal2. Now that you are in your command prompt/terminal, run the following command:    ```text    cd desktop    ```3. Next, move your command prompt/terminal's location to the new `python_course` you just created by running the following:    ```text    cd python_course    ```4. Create a _new_ directory within the `python_course` directory. This new folder is the project you will be working in for this lesson. Run the following:    ```text    mkdir lesson_seven    ```5. Open up a new window in VSCode.6. Open the `lesson_seven` directory in VSCode7. Create a new file named `main.py`Once the `main.py` file is created, you are ready to go! As you work through this lesson, add the code examples into your project so you can see the output yourself. Remember, to see the output within the VSCode terminal, right-click within your file and choose "Run Python File in Terminal".The creation of this new project is for you to practice your new skills. It is highly recommended that you add the code from this lesson into your `lesson_seven` project as you learn it. As you are going through this lesson and adding code to your project, you may find it helpful to include `comments` with a brief sentence explaining what is going on in the code. That way, you will have an easy reference to the topics explained in this lesson. Happy coding!  Page 2 - Standard Library[Back to Top](DS109L7_toc)  Standard LibraryPython's standard library contains data types, built-in functions, and exceptions as well as objects that can be used by _all_ Python code. The bulk of the library consists of a collection of modules. Some of these modules are written in the C language and built into the Python interpreter; others are written in Python and must be imported. Some of these modules provide interfaces that are specific to particular operating systems, such as access to a specific piece of hardware.You've already seen several of the built-in functions that are part of the Python standard library. The most common one you've seen thus far is `print()`, which outputs information to the standard output device (which has been VS Code's integrated terminal so far). You've also seen `len()`, which returns the number of items in a collection or the number of characters in a text string.Some other built-in functions you'll find useful are `str()`, which is used to convert the given object into a _string_; `min()`, which returns the smallest value in a collection or a list of two or more arguments.```pythonpi = 3.14159pi_string = str(pi)print("The value of Pi is " + pi_string)number_list = [33, 19, 25, 7, 18]min_number = min(number_list)print("The minimum number in the list is " + str(min_number))```**OUTPUT**:```The value of Pi is 3.14159The minimum number in the list is 7```You can read about all of the available built-in function of Python's library at the link below:> [View the built-in functions of the Python standard library](https://docs.python.org/3/library/functions.html).Next you will learn about a few Python standard modules that you can use for specific functionality. However, in order to use them, you need to learn about modules and importing them into your program.  Page 3 - Modules[Back to Top](DS109L7_toc)  ModulesA `module` is groups of related code, including classes and functions, that allows you to logically organize your Python code. Creating modules of re-usable code is the goal. As you grow into developing Python programs, you'll eventually find yourself writing the same or similar functions and classes in several of them. Putting that code in modules and importing them into your new program will save you time and money.The most straightforward approach to creating a module is placing the related code into a single Python file, with the extension ".py" as you've seen throughout this course. In it, you would place your variables, classes, and functions. Once you've created a module, you can reuse the code by importing it into your new code. This mechanism, thus, allows you to import code from other developers to use in your programs.To illustrate, go ahead and create two files in the same directory (folder). Name one of them `icecream.py` and the other `icecream_cone.py`.Add the following code snippet to the `icecream.py` file.icecream.py file:```pythondef scoop_icecream(size, *toppings):    """Give a summary of the ice cream cone you are making."""    print("\nMaking a " + size + " ice cream cone with the following toppings:")    for topping in toppings:        print("- " + topping)```Next, in your `icecream_cone.py` file add the following:icecream_cone.py file:```pythonimport icecreamicecream.scoop_icecream('small', 'sprinkles', 'chocolate', 'cherries')icecream.scoop_icecream('large', 'peanuts')```Run the file in the terminal and you should see the output below.**OUTPUT:**```textMaking a small ice cream cone with the following toppings:- sprinkles- chocolate- cherriesMaking a large ice cream cone with the following toppings:- peanuts```Now, these code samples will be broken down to help you understand what's going on.Starting with the `icecream.py` file:- The function `scoop_icecream` is defined with two parameters `size` and `toppings`. The asterisk `*` in front of the `toppings` parameter indicates that you can pass in one or more values for toppings when calling the function.- The function `scoop_icecream`, when called, prints to the console a message that includes the passed values of `size` and `toppings`. Due to the `*` you see preceding the `toppings` parameter, you can treat `toppings` like a collection, which is why you see the `for` loops to print the toppings.Next, the `icecream_cone.py` file:- `import icecream` - This line pulls in (imports) the code from the other file `icecream.py`, giving you access to the `scoop_icecream` function defined in it. The keyword `import` is followed by the name of the file __without__ the `py` extension. You never add the `py` extension when you import files.- The next two lines call the function `scoop_icecream` that was imported, passing in different sets of toppings (remember the *). As you can see, the function name is prefixed with `icecream.`, which is the name of the module file and a dot. So, when calling an imported function, you see that you specify the module file name, followed by a dot `.`, then the function name. You will see variations to this shortly.--- importThe keyword `import` tells Python to open the file and copy all the function from it into the current program. You do not see this occurring, though; Python does all of this behind the scenes as the program runs. Once imported, any function that is in the targeted file will be available in your current file.You can import an entire module, making every function and class it contains available to your program:```pythonimport icecream```--- Using Functions from Imported ModuleTo call a function from an imported module, enter the name of the module you imported, followed by the name of the function separated by a dot(`.`).Here is the syntax used to invoke a function from an imported module.```pythonmodule_name.function_name()```--- Importing Specific FunctionsIf a module is large, but you only need one function, there's no point plugging up memory with unnecessary code; you can import a single function. Below is the general syntax:```pythonfrom module_name import function_name```Above, you can see the keywords `from` and `import` are used. When importing a specific function, you use the `from` keyword to specify the module from which it will be imported. You then use the `import` keyword to specify the specific function you wish to import.You can also import as many functions as you would like from a module by separating each function name with a comma like so:```pythonfrom module_name import function_1, function_2, function_3```Below shows an example of importing one function using the ice cream example:```pythonfrom icecream import scoop_icecream```When you import a function in this fashion, you no longer need to use the dot notation when calling the function. Instead of doing _module.function()_, you can simply do _function()_. In the example below, the `scoop_icecream()` function is imported specifically, and then called:```pythonfrom icecream import scoop_icecreamscoop_icecream('small', 'sprinkles', 'chocolate', 'cherries')```--- asWhen you import a module, what if there's a function that is defined that has the same name as a function in the new file, or in another module you've already imported? Fortunately, Python provides a mechanism for giving an imported function an alias: `as`.```pythonfrom icecream import scoop_icecream as scoopscoop('small', 'sprinkles', 'chocolate', 'cherries')```The `import` statement above renames the function `scoop_icecream()` to `scoop()` in this specific file. Anytime you want to call `scoop_icecream()`, you can now call `scoop()` instead.In general, the syntax is as follows:```pythonfrom module_name import function_name as alias```Not only can functions be given an alias, but modules can be given an alias as well. Giving a module a short alias like `i` for `icecream` allows you to call the module's functions more quickly. Calling `i.scoop_icecream()` is more concise than calling `icecream.scoop_icecream()`.```pythonimport icecream as ii.scoop_icecream('small', 'sprinkles', 'chocolate', 'cherries')```When giving the module an alias, remember that all the function names will retain their original names. Calling `i.scoop_icecream()` is not only more concise than writing `icecream.scoop_icecream()`, but also directs your attention from the module name and allows you to focus on the more descriptive names of the functions. The function names, which tell you what each function does, are more important to the readability of your code than using full module names.The general syntax for assigning an alias to a module is:```pythonimport module_name as alias```--- Importing All FunctionsYou can tell Python to import every function from a module by using the asterisk `*` operator. Of course, anytime you import a large amount of functionality, be sure to check if there are any conflicts.```pythonfrom icecream import *scoop_icecream('small', 'sprinkles', 'chocolate', 'cherries')```In the example above, all functions are imported using the `*` (although there's currently only one function in the file). This allows for the use of the function name without having to include the module name and dot notation for all of the imported functions.---- Importing ClassesWhat you learned about importing a specific, multiple, or all functions also applies to classes. The general syntax for importing a class is below:```pythonfrom module_name import class_name[, more_class_names]|*```The above general notation includes some syntax you've not yet seen. The square brackets `[]` indicate something is optional. Above, this mean that you can import a class name and optionally more class names separated by a comma. The pipe symbol `|` is used to separate options from which you choose one. Above, the option is to either choose one or more class names or to use the asterisk `*` to import all of them.Also, when importing a specific class, you can set an alias just like you can with a function. You can even import functions and classes, both with aliases, in a simple import statement.```pythonfrom module_name import function_name as function_alias, class_name as class_alias```  Page 4 - Python Standard Modules[Back to Top](DS109L7_toc)  Python Standard ModulesNow that you understand modules, you will be introduced to Python's library of standard modules. To start off, Python includes two modules that are useful for interacting with the Python system itself. These modules are `sys` and `keyword`. The `keyword` module contains a list of all Python reserved keywords. The `sys` module allows you to explore many features including the _Interactive Mode_ help system.---- sysTo import this module, the syntax is the same as if you were importing a module you created.```pythonimport sys```Now that `sys` (or _system_) has been imported, you can access the version of Python:```pythonimport sysprint('Python Version:', sys.version)```**OUTPUT:**```htmlPython Version: 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06)[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]```What if you wanted to locate the Python interpreter?**INPUT:**```pythonimport sysprint('Interpreter Location:', sys.executable)```**OUTPUT:**```htmlInterpreter Location: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3```--- keywordLike for `sys`, you need to import this module:```pythonimport keyword```With the `keyword` library, you can print out a list of Python's reserved keywords with the following syntax:```pythonimport keywordprint('Keywords: ')for word in keyword.kwlist:    print(word)```**OUTPUT:**```htmlKeywords:FalseNoneTrueandasassertbreakclasscontinuedefdelelifelseexceptfinallyforfromglobalifimportinislambdanonlocalnotorpassraisereturntrywhilewithyield```You can also check to see if a word you'd like to use is a reserved keyword or not by using the `iskeyword()` method.```pythonimport keywordprint(keyword.iskeyword('def'))```**OUTPUT:**```htmlTrue```Python returns `True`, in the above example, because `def` is a reserved keyword (used to define a function).Many developers that use Python perform a lot of mathematical operations, and Python has a math module with numerous built-in functions that you will learn about next.  Page 5 - The **math** Module[Back to Top](DS109L7_toc)  The **math** ModulePython's library also includes a `math` module that provides a plethora of methods you can use to perform mathematical operations.Importing the `math` modules into your code will give you access to such functions as `floor()` and `ceil()`. The first rounds a floating point number down to the nearest integer, while the second rounds up.* **`math.ceil()`** - This function rounds **up** to the nearest integer.* **`math.floor()`** - This function rounds **down** to the nearest integer.If you were to print out the results of a call to these functions, you would see that although they are whole number integers, the data type is still a float. So, instead of 4, you'd see 4.0, for example.You'll also have access to functions like `pow()` and `sqrt()`:* **`math.pow(x,y)`** - This function returns a float of _x_ raised to the power _y_.* **`math.sqrt(x)`** - This functions returns a float of the square root of _x_.Below you'll find an example of each of the above functions. Take note of the first comment to remind you about importing entire modules and the need for dot syntax.```python since the entire module is imported, the module name must precede the function names (dot syntax)import math round 8.5 down using `floor`print("Round the number 8.5 down: ", math.floor(8.5)) round 8.5 up using `ceil`print("Round the number 8.5 up: ", math.ceil(8.5)) compute 5^10 using `pow`print("5 to the power of 10 = ", math.pow(5, 10)) compute the square root of 82 using `sqrt`print("The Square Root of 82 is: ", math.sqrt(82))```**OUTPUT:**```html895 to the power of 10 =  9765625.0The Square Root of 82 is:  9.055385138137417```--- The **random** ModulePython includes a `random` module that can be used to produce pseudo-random numbers once imported into a program. Below are a few of the functions that are available from the `random` module.* **`random.random()`** - Produces a single floating-point number between `0` and `1.0`.* **`random.sample()`** - Produces a list of elements selected at random from a sequence. This function requires two arguments to specify the sequence to select from, and the length of the list to be produced. Using the `range()` function will allow you to specify a sequence as the first argument.Using the `random` module, here's an example of using `random.random()`:```pythonimport randomprint("A random float between 0 - 1.0: ", random.random())```**OUTPUT:**```htmlA random float between 0 - 1.0:  0.7939999233344973```Now, the second function `random.sample()`:```pythonimport randomnumbers = random.sample(range(1, 49), 7)  The first argument given is the range from 1 to 49. The second argument is how many numbers you want to be returned from that range.print('Your lucky numbers are: ', numbers)```**OUTPUT:**```htmlYour lucky numbers are:  [42, 43, 36, 6, 44, 31, 23]```You've now seen a few of some common built-in functions available to you via the Python standard library. There are many more! You can find the rest in the [Python Docs](https://docs.python.org/3/library/index.html).---  Page 6 - Modules Activity[Back to Top](DS109L7_toc) or this exercise, you will need to __import__ the `math` and `random` Python modules.Generate a random number between 0 and 100 and store it in the variable `my_random`. Remember, the `random` method returns a value between 0 and 1. You can scale it by multiplying the result by 100.Compute the _square root_ of `my_random` and store the result in the variable `square_root`.__Note__: If you do not see any output in the preview window, it may be due to failing to import the correct module(s).<jupyter_code>import math
import random

my_random = random.random() * 100
square_root = math.sqrt(my_random)

print(square_root)<jupyter_output>1.5927249528945506
StarcoderdataJupyterStructuredCleanDedup