Python Programming 10
Enough of OOP for now. Let's talk about making life easier. Modules and File IO.
In this last chapter of the basics of Python, I will be using Sublime and PyCharm (totally fine to use either). If you are on a Mac, you can probably choose which one you want. If you are on Windows, you must use PyCharm to compile the Python properly (for these lessons).
Modules make it easy for you to import code that isn't yours. When programming professionally, you are usually working with many other people trying to create an application. It is generally a good idea to not repeat yourself (DRY) so not reinventing every wheel is essential to making progress. It is very easy for you to drag in entire libraries of code that you have not written which you can use to make you app just that much cooler, much faster.
import math
print math.sqrt(111111)
When you run this program, you will get 333. This is to be expected because the square root of 111111 is 333. However, we didn't write a function that can compute square roots. We are able to come to this answer because we imported the math library. Python has many libraries built in and many which you can download and install externally. The 'math' library is one of the built in libraries. It contains many different functions of advanced math that were created so you don't have to remake those functions. All you need to do is import the library and use them.
File IO is essential to computers. We input and output files and information everyday with our emails, texts, and videos. With python, reading and writing files is very easy. We must start in PyCharm with two files. The first is your regular python file you always code with. The second is one you must create called 'foo.txt'. We are just making a text file inside the same directory as our code. Next we want to open our text file and type in "I am a foo file". Then write the following code in the python file.
foo = open('foo.txt', 'r+')
str = foo.read()
print str
foo.write('\nNo Youre not!')
foo.close()
When this code runs, the output in the console will be "I am a foo file". In the foo.txt file another line will be written in saying "No Youre not!". What we did was create a variable called foo which opened the foo.txt file for reading and writing. Then we stored the 'read' data of the foo variable in a variable called str. We printed str which gave us the line in foo.txt. Next we wrote inside of foo the string saying "No youre not!". Then we closed the foo file to ensure the process. This is a basic example of file IO in Python.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Make a text file with the squares of numbers 1-25 (1,4,9,16,25....). Then make a program which takes those squares in and finds the square root of each. Then write the suareroots back into the text file. (This is very difficult)