Академический Документы
Профессиональный Документы
Культура Документы
by Anuar Lezama
SOME WORDS
The following document intents to provide a basic introduction to Python. We will go from
installation to develop some simple programs and review some of the functions and operability
of the language. You can go to the Reference section and see some of the links provided, most
of the material available is for free, I strongly recommend trying at least one of the books posted
such as Learn Python the Hard way or Invent your own computer games with Python.
Coursera is also an amazing tool, go check it out and see the courses available all for free.
I will try to do this document as simple as possible and avoid all the extra words and paragraphs
that you will normally find in a more formal document. Like this introduction! So lets go and get
started!
WHATS PYTHON ?
This is one of those existential questions that does not have a specific answer, so why?
Because you can, because is a high-level language, because you can do a lot of stuff and it is
pretty cool.
Python was developed in the late 1980s by a guy called Guido Van Rossum at CWI (Centrum
Wiskunde & Informatica) in the Netherlands. Python is a multi-paradigm programming language
because it supports both object-oriented and structured programming.
Pythons core philosophy pretty much resumes its capabilities.
INSTALLING PYTHON.
Pretty much this is very straigh forward, just go to the page python.org/download/ and select the
operative system you work with and click. Download the program and follow the instructions.
Select the location where you want to install it, like on your (C:) System.
Now go to start > all programs and find Python, then click on the IDLE (Python GUI) tool.
Something like the following window should appear.
We are going to work on two places basically one is the Python Shell or IDLE (Integrated
development environment for Python), check the following link for more info:
docs.python.org/2/library/idle.html
And the text editor, which is when you open a new window from the Python Shell and type your
program.
Python has some basic math built in function, that are located in the __builtins__ module, for
some other more complicated functions you will have to import the math module. Modules are
like libraries with a lot of functions inside, you import them and then select what functions you
will use.
Try doing division, multiplication and subtraction. If you want to do exponentials you have to
type double * for example 2 **8. Type and press enter
All functions in python start with def. So lets write down our function. Open IDLE and click
File>New Window. This New window is our text editor and here we are going to write our
function. So type the following and then save it as triangle_area.py. Save it in the folder where
python is (C:/Python33/).
Write the following:
Notice that we use return to get the value of the formula we have just typed.
Save it and then press F5 or click Run> Run Module. This will make your little program run in
IDLE, check for any errors. Now that we have our program running, we do not see anything
because we have not specified what the values of our triangle are.
Now that your program is running, in IDLE, type the values of base and height and press enter.
So far so good!, try typing some other values and double check them either in python, or get a
calculator.
Our triangle program runs perfectly we have tested it out, but it is missing some information,
some comments and extra information about what it does.
Python supports two style of commenting, one with triple quotation and another with hash tag.
The first one is a multiline comment, you type triple quotation to open the multiline comment and
then you close it with another triple quotation. Lets open our triangle program and add some
info.
If you use triple quotation you can write multiple lines without a problem as longs as everything
is inside this quotations. If you are using the hash tag then you have to start all your comments
with a hash tag.
Header
Type Contract
Description
Examples
Body
Lets solve the following problem and write it following the proper design recipe.
-
Now the other obvius example we can write is the boiling temperature in Fahrenheit. So lets do
that.
Step 2. Type Contract Figure out the type contracts, what types are the parameters and what
types are the values it returns. In this case we are working with integers but also floats can be
used so we are going to type in numbers and we are getting numbers as well.
Step 3. Header. Now that we have written some calls and know what the type (contract) should
be it is time to write the header of the function. Pick a meaningful parameter names, so that
other programmers and you have an easier time understanding your function. So we have
decided that our function will be named convert_to_celcius and we know that our parameter is
the number of degrees in Fahrenheit, so we will use fahrenheit as our parameter name.
Everything below the function Header should be a doc string.
Step 4. Description. What does our function do? We must mention every parameter in our
description as well as the return value!
Step 5. Body. Here we write the code of our program. As we learned from school, we substract
32 from Fahrenheit degrees and then we multiply it by 5 / 9.
Step 6. Testing Save your program and run it, you can press F5 on Windows, or just click
Run>Run Module. Now lets test it with our examples, lets convert 32 F and 212 F and see what
results are appearing.
Looks like our program works perfect, except that it is returning a float number, lets fix this in
our Type Contract, instead of having (numbers) -> numbers lets write (number) -> float. And
lets fix our examples as well. Instead of 0 we type 0.0 and instead of 100 we type 100.0.
NOTE: Division always returns a float number.
Perfect we have created our first program following the proper design recipe.
LESSON 4 DOCTEST.
From docs.python.org/2/library/doctest.html
The doctest module searches for pieces of text that look like interactive Python
sessions, and then executes those sessions to verify that they work exactly as
shown.
This is one of the most useful tools in python. doctest module lets you test your code and check
if it is returning values as you expect. For this we will create a new document with different
functions. Open IDLE and go to File>New Document. We are going to create a document with a
couple of functions that will calculate different things. Open the triangle._area and save it as
functions.py. Also write some other examples of how the function must respond. See the
example.
When writing examples try to cover all of the cases you are going to handle, if you function is
expecting values over 0 or below 0 or even negatives, try to think about all the cases and write
down the examples. Be sure that all the examples are aligned and that you are leaving a blank
space between your last example and the end of the multiline comment. Run your program,
press F5 or go to Run>Run Module. Go to Python Shell (IDLE) and type the following and press
enter.
This means we ran all 5 examples we wrote and got 0 failed. So far so good, lets add some
other functions to our functions.py document. Now we are going to add a function that
calculates the area of a square. Type the following:
If you think of other examples we are not adding please go ahead and add them. Now run you
program and run the doctest.testmod(). You should see something like this:
Lets add two more functions one function that calculates the area of a rectangle and the area of
a circle. The first one is very straight forward. The area of the circle is going to require a little bit
more. Try doing the rectangle function by yourself so we can jump ahead and do the circle
function.
From school we learned that the circle area is the value of pi multiplied by the radius to the
power of two.
There seems to be no problem with this formula, we can assigned the value of pi or even type it,
but there is a module in python that handles the value of pi. Go to the shell and type import
math and then dir(math).
Whenever you want to see what the module contests are, after importing it, just type
dir(module_name). If then we decide to use a function of this module we must import the
module first and then specify what function we are using.
See that we had to type math.pi instead of just pi, because we are telling Python that we are
going to use the value of pi that is inside the math module. Go to the shell and type the
following.
Now we write our circle_area function. But we have a problem; the values of the area are float
with too many numbers after the floating point. Go too Google and type Calculator, now try to
find the area of a circle with radius 5.
We have to round this value to 2 numbers after the floating point. As we mentioned before
Python has some in built functions that are inside the __builtins__ module and you do not have
to import this module it is always available. We are going to use round to round up our values
to 2 digits after the floating point. Type dir(__builtins__).
If you want to know how to use a function type help(function_name). Lets do this for round
and see how the function works
As you can see the function takes a number, and then the ndigits to round up, if you do not put
the ndigits python will assume that it is 0, so if you have 14.2222 and you do round(14.222)
you will get 14.
Now we write the code and generate some examples. You can use python to calculate the
examples or go to google calculator. Do not forget to import math, do this at the very top of
the functions.py file.
Now run the program, type F5 or click Run > Run Module. You should get something like this:
References:
[Web Page] Python.org
Home page of Python.
[Book] Learn Python The Hard Way
http://learnpythonthehardway.org/
[Book] Dive into Python (for Python 3)
http://www.diveintopython3.net/
[Book] Invent your own Computer Games with Python
http://inventwithpython.com/
[Course] Learn to Program: The Fundamentals
https://class.coursera.org/programming1-2012-001/class/index
[Course] An Introduction to Interactive Programming in Python
https://class.coursera.org/interactivepython-002/class/index
[Tool] CodeSkulptor.org
CodeSkulptor runs Python programs in your brower.