To the student: Why Python?

                                To the student: Why Python?

                               Given so many other programming languages in the world, why should you learn Python as your first exposure to computer programming? Well, the real answer is that your instructor selected the both the language and this textbook for the course, so what choice do you have? Nonetheless, let me explain why this was a very good decision.Python is easy, Python is fun, Python is educational, and Python is powerful.
                          Let’s start with the powerful. If you look at the case studies toward the end of the session, you will see that you will end up learning how to do some very interesting things. Tasks like writing your own blog, automatically solving soduko puzzles, reading your iTunes database, or writing a wiki. None of these take more than a page or two of Python code.
                        This is considerably smaller than the equivalent programs would be in almost any other programming language. Is it easy? Let me fudge and say it is easier. Computer programming in any language takes skill, organization, logic, and patience. Python is no different in this regard. What makes Python attractive is that you can begin so quickly and easily. Your first Python
program can be as simple as 2 + 3:
>>> 2 + 3
5
Thereafter the path to learning how to create your own complex applications is, we hope, at least clearly laid out, even if it will take some effort on your part.
Active Learning:                                 
                               This session  follows an attitude towards teaching that has been termed active learning. Rather than treating you, the student, as a passive repository into which knowledge is poured, active learning tries to engage you, the student, as a fully equal partner in the process of learning. Rather than simply telling you how some feature works, I will usually suggest experiments that you can perform to discover the answer on your own. 
                                          There are several benefits to this approach. First, it makes you use a different part of your brain than you would if you were simply reading. Second, it gives you, the student, a greater sense of ownership of the knowledge. Third, experimentation is often the fun part of programming. Lastly, by encouraging you to experiment in the discovery of simple information, I hope to instill habits that you will continue to carry with you throughout your programming career. Together, the intent is that active learning helps you more easily retain and use the information you have learned.


History of python

 History of python

                                       Python was designed by Guido van Rossum while he was working at the CWI (the Centrum voor Wiskunke and Informatica; literally “center for wisdom and informatics”) a world-class research lab in the Netherlands. The CWI group he was associated with designed a programming language called ABC.  ABC was clearly intended as a pedagogical tool for teaching programming, and a great deal of work went into developing both the language and associated teaching material.1 The language ABC had a number of features that were impressive for the time: a tightly integrated development environment, interactive execution, high level data types (lists, dictionaries, tuples and strings), dynamic memory management, strong typing without declaration statements and more. 
                      The idea to use indentation for nesting, and eliminate the brackets or BEGIN/END keywords found in most other languages, was taken directly from ABC. So was the idea of dynamic typing. Software development in ABC was both rapid and enjoyable, and totally unlike almost any other competing language. (The one exception might be Smalltalk, which was just becoming well known in 1985. Indeed, during my time at the CWI I was writing a book on Smalltalk, and part of the work I performed during that year was to explain to my colleagues in the ABC group the basic ideas of Object-Oriented programming, which I myself was only just beginning to understand)
                     
                      Guido started designing Python around 1990. For those familiar with the earlier language the heritage of ABC in Python is clear. Guido discarded some of the annoying features of ABC, and kept all the best ideas, recasting them in the form of a more general-purpose language. By then the mechanisms of object-oriented programming were well understood, and the language included all the latest features. He added a number of features not found in ABC, such as a system for modularization and including libraries of useful utilities. Python was released to the world in 1991, and very quickly attracted a loyal following. 
                        Python’s design turned out to be general enough to address a much wider range of applications than ABC. (To be fair, the designers of ABC were focused on teaching, and never intended the language to be general-purpose). The features that programmers appreciated in 1990 are still the same today: ease of use, rapid software development, the right set of data types that help to quickly address most common programming problems.

Python Monty:


The name, by the way, owes nothing to the reptile and everything to the 1970’s BBC  comedy series Monty Python’s Flying Circus. Many die-hard Python programmers enjoy  making sly references to this series in their examples. You don’t need to have seen Monty  Python’s Life of Brian, The Meaning of Life, And Now for something Completely  Different, or Monty Python and the Holy Grail or even Spamalot in order to become a  Python programmer, but it can’t hurt, either.


what is python

                what is python

                                                   For those looking for buzzwords, Python is a high-level, interpreted, reflective, dynamically-typed, open-source, multi-paradigm, general-purpose programming language. I could explain each of those terms in detail, but in the end the result would still not convey what makes Python programming different from other languages. There is no one thing in Python that is not found in other languages, but it is the elegant design and combination of these features into a single package that makes Python such a pleasure to use.
                    Python is sometimes described as a scripting language, for the simple reason that thousands of working programmers daily use the language in this fashion. That is, they use Python as a tool to quickly and easily glue together software applications and components written in many different languages. But such a categorization is far too narrow, and Python can justly be described as a general-purpose language, one that can you can use for almost any programming task you would like to perform.
                      This is not to say that Python is the only programming language you will ever need or will ever learn. A working computer scientist should know how to use many different tools, and that means he or she should have an appreciation of many different types of language. For example, because Python is interpreted, the resulting programs are often not as fast as those written in lower-level languages, such as C or C++.
                     On the other hand, programs are much easier to write than they are in C. So there is a trade-off, anengineering compromise of the type common in computer science. Is less time in execution of the final program worth spending more time in development and debugging? For the beginning student, and in fact for the vast majority of computer programs, the answer is clearly no. (Another way to express this trade-off is to ask, “whose time is more important, your time or the computer’s?”) Low-level languages such as C have their place, but only for the small group of computer programs for which ultimate execution time is critically important. You may eventually work on such systems, but not in your first programming course.
              Another important category of programming languages are those tied to a specific application. A good example of this category is the language PHP, a programming language used to create interactive web pages. (See www.php.org). A general-purpose language, such as Python, cannot hope to be as easy to use in this application area. But PHP is extremely clumsy to use for purposes other than web pages. If, or when, you start extensive work in such an application area you will want to learn how to use these tools


Python's feature

Python's feature highlights include:
Ø  Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time.
Ø  Easy-to-read: Python code is much more clearly defined and visible to the eyes.
Ø  Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain.
Ø  A broad standard library: One of Python's greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.
Ø  Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code.
Ø  Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
Ø  Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.
Ø  Databases: Python provides interfaces to all major commercial databases.
Ø  GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.
Ø  Scalable: Python provides a better structure and support for large programs than shell scripting.
Apart from the above mentioned features, Python has a big list of good features, few are listed below:
Ø  Support for functional and structured programming methods as well as OOP.
Ø  It can be used as a scripting language or can be compiled to byte-code for building large applications.
Ø  Very high-level dynamic data types and supports dynamic type checking.
Ø  Supports automatic garbage collection.
Ø  It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

How to install Python

                  installation Python

                               For Python programming you need a working Python installation and a text editor. Python comes with its own editor IDLE, which is quite nice and totally sufficient for the beginning. As you get more into programming, you will probably switch to some other editor like emacs, vi or another.
                      The Python download page is http://www.python.org/download. The most recent version is 3.1, but any Python 2.x version since 2.2 will work for this tutorial. Be careful with the upcoming Python 3, though, as some major details will change and break this tutorial's examples. A version of this tutorial for Python 3 is at Non-Programmer's Tutorial for Python 3. There are various different installation files for different computer platforms available on the download site. Here are some specific instructions for the most common operating systems:

Linux, BSD and Unix users: 

                     You are probably lucky and Python is already installed on your machine. To test it type python on a command line. If you see something like that in the following section, you are set.If you have to install Python, just use the operating system's package manager or go to the repository where your packages are available and get Python. Alternatively, you can compile Python from scratch after downloading the source code. If you get the source code make sure you compile in the Tk extension if you want to use IDLE.

Mac users :

                  Starting from Mac OS X (Tiger), Python ships by default with the operating system, but you might want to update to the newer version (check the version by startingpython in a command line terminal). Also IDLE (the Python editor) might be missing in the standard installation. If you want to (re-)install Python, have a look at theMac page on the Python download site.

Windows users 

                Some computer manufacturers pre-install Python. To check if you already have it installed, open command prompt (cmd in run menu) or MS-DOS and type python. If it says "Bad command or file name" you will need to download the appropriate Windows installer (the normal one, if you do not have a 64-bit AMD or Intel chip). Start the installer by double-clicking it and follow the procedure.


Very simple programs

                        We have Python installed, now what? Well, we program! And it is that simple (at least for now!). Python makes it easy to run single lines of code—one-liner programs. Let's give it a go.
Opening IDLE:
                       Run the program labelled IDLE (Stands for Integrated Development Environment). Now you are in the IDLE environment. This is the place you will be spending most time in. Here you can open a new window to write a program, or you can simply mess around with single lines of code, which is what we are going to do. Type the following and press enter (don't type '>>>' as it should already be there but yes in python 3.0 you have to add(" sin to start after using print command and ") for closing or it will show an error message...

Code Example 1 :
Hello, world!
>>> print ("Hello, world!")


                       What happened? You just created a program, that prints the words 'Hello, world'. The IDLE environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g., defining a few variables, and then testing to see if a certain line will work. That will come in a later lesson though.

Math in Python:
Now try the following examples. I've given explanations in parentheses.
Code Example 2 :
>>> 1 + 1
2
>>> 20 + 80
100
>>> 18294 + 449566
467860
(These are additions.)

>>> 6 - 5
1
(Subtraction)

>>> 2 * 5
10
(Multiply, rabbits!)

>>> 5 ** 2
25
(Exponentials; e.g., this one is 5 squared)

>>> print "1 + 2 is an addition"
1 + 2 is an addition
(The print statement, which writes something onscreen. Notice that 1 + 2 is left unevaluated.)

>>> print "One kilobyte is 2^10 bytes, or", 2 ** 10, "bytes."
One kilobyte is 2^10 bytes, or 1024 bytes.
(You can print sums and variables in a sentence.
        The commas separating each section are a way of
        separating clearly different things that you are printing.)

>>> 21 / 3
7

>>> 23 / 3
7
(Division; note that Python ignores remainders/decimals.)

>>> 23.0 / 3.0
7.666666666666667
(This time, since the numbers are decimals themselves, the answer
        will be a decimal.

>>> 23 % 3
2

>>> 49 % 10
9
(The remainder from a division)

                    As you see, there is the code, then the result of that code. I then explain them in brackets. These are the basic commands of Python, and what they do. Here is a table to clarify them (because tables look cool, and make you feel smarter ;) ):

Order of Operations ::
Here are some examples that you might want to try, if you're rusty on this:
Code Example 3 :
>>> 1 + 2 * 3
7
>>> (1 + 2) * 3
9
                  In the first example, the computer calculates 2 * 3 first, then adds 1 to it. This is because multiplication has the higher priority (at 3) and addition is below that (at a lowly 4).
In the second example, the computer calculates 1 + 2 first, then multiplies it by 3. This is because parentheses (brackets, like the ones that are surrounding this interluding text ;) ) have the higher priority (at 1), and addition comes in later than that.
              Also remember that the math is calculated from left to right, unless you put in parentheses. The innermost parentheses are calculated first. Watch these examples:
Code Example 4 :
>>> 4 - 40 - 3
-39
>>> 4 - (40 - 3)
-33
In the first example, 4 - 40 is calculated,then - 3 is done.
In the second example, 40 - 3 is calculated, then it is subtracted from 4.

              The final thing you'll need to know to move on to multi-line programs is the comment. Type the following (and yes, the output is shown):
Code Example 5  (Comments)
>>> #I am a comment. Fear my wrath!

>>> 
               A comment is a piece of code that is not run. In Python, you make something a comment by putting a hash (#) in front of it. A hash comments everything after it in the line, and nothing before it. So you could type this:
Code Example 6 ( Comment examples)
>>> print "food is very nice" #eat me
food is very nice
(A normal output, without the smutty comment,
thank you very much)

>>># print "food is very nice"

(Nothing happens, because the code was after a comment)

>>> print "food is very nice" eat me

(You'll get a fairly harmless error message,because you didn't put your comment after a hash)

                Comments are important for adding necessary information for another programmer to read, but not the computer; for example, an explanation of a section of code, saying what it does, or what is wrong with it. You can also comment out bits of code if you don't want them to compile, but can't delete them because you might need them later.

Variables& Scripts

Variables, Scripts

Well, we can make one-liner programs. So what? You want to send programs to other people, so that they can use them, without knowing how to write them.
Editing in Notepad: 
              Writing programs in Python to a file is very easy. Python programs are simply text documents—you can open them up in Notepad (or another text editor), and have a look at them, just like that. So, go and open Notepad. Type the following:
Code Example 1 – mary.py
#A simple program.
print "Mary had a little lamb,"
print "its fleece was white as snow;"
print "and everywhere that Mary went",
print "her lamb was sure to go."
Keep this exactly the same, down to where the commas are placed. Save the file as mary.py—and make sure Notepad doesn't add .txt to the end of the filename (you will have to tell it to save as any file to avoid this). Turn off 'Hide known file extensions' in Windows Explorer, if it makes it easier.
Using the IDLE environment :
                   Now, open up the Python IDLE program (should be in your start menu). Click 'File > Open' and find mary.py and open it. If you can't find mary.py, set the open dialogue to 'Files of type: All Files (*)'. A new window will open, showing the program you just wrote. To run your program, click 'Run > Run Module' (or just press F5). Your program will now run in the main Python screen (titled 'Python Shell') and will look like this:
Code Example 2 – mary.py output
Mary had a little lamb,
its fleece was white as snow;
and everywhere that Mary went her lamb was sure to go.

                You can also use IDLE to create Python programs, like what you did in Notepad. Simply click 'File > New'. We will be writing all of our programs now in the Python IDLE program—the Notepad thing is just a demonstration to tell you that a .py file is just a simple text file, which anyone can see.
There are a couple of things to notice here:
Ø  First of all, the comment wasn't shown. That is good, because remember—comments aren't compiled. (Try compiling it after removing the #—it comes out messy.)
Ø  Second, is that the 3rd and 4th line got joined. This is because there is a comma just outside the inverted commas that surround the text. In the print command, this stops the program from starting a new line on the screen when showing text.
Ø  You can also run the program from your command line program (e.g., cmd). Open the prompt up, type cd path\to\your\file then type python mary.py. Your program will now execute in the command line.
Variables :
                     Now let's start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let's make a program that uses variables. Open up IDLE and click 'File > New Window'. A new window now appears, and it is easy to type in programs. Type the following (or just copy and paste—just read very carefully, and compare the code to the output that the program will make):
Code Example 3 – Variables
#Variables demonstrated
print "This program is a demo of variables."
v = 1
print "The value of v is now", v
v = v + 1
print "v now equals itself plus one, making it worth", v
v = 2
print "v can store any numerical value, to be used elsewhere."
print "For example, in a sentence. v is now worth", v
print "v times 5 equals", v * 5
print "But v still only remains", v
print "To make v five times bigger, you would have to type v = v * 5"
v = v * 5
print "There you go, now v equals", v, "and not", v / 5
Note that if you just want to modify a variable's value with respect to itself, there are shortcuts. These are called augmented assignment operators:
Table 1 – Augmented operators
Standard form
Augmented
v = v + 5
v += 5
v = v – 5
v -= 5
v = v * 5
v *= 5
v = v / 5
v /= 5

Strings :
              As you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:
Code Example 4 – Strings
#Giving variables text, and adding text.
word1 = "Good"
word2 = "morning"
word3 = "to you too!"
print word1, word2
sentence = word1 + " " + word2 + " " + word3
print sentence
The output will be:
Code Example 5 – String output
Good morning
Good morning to you too!

                As you see, the variables above were holding text. Variable names can also be longer than one letter—here, we had word1, word2, and word3. As you can also see, strings can be added together to make longer words or sentences. However, spaces aren't added in between the words—hence me putting in the " " things (there is one space between those).

Loops&Conditionals

                        Loops, Conditionals

                         Just imagine you needed a program to do something 20 times. What would you do? You could copy and paste the code 20 times, and have a virtually unreadable program. Or, you could tell the computer to repeat a bit of code between point A and point B, until the time comes that you need it to stop. Such a thing is called a loop.
The while loop:
The following are examples of a type of loop, called the while loop:
Code Example 1 – The while loop
a = 0
while a < 10:
    a = a + 1
    print a
How does this program work? Let's go through it in English (this is called pseudocode):
Code Example 2 – Plain-language while loop
'a' now equals 0
As long as 'a' is less than 10, do the following:
    Make 'a' one larger than what it already is.
    print on-screen what 'a' is now worth.
What does this do? Let's go through what the computer would be 'thinking' when it is in the while loop:
Code Example 3 – while loop process
#JUST GLANCE OVER THIS QUICKLY
#(It looks fancy, but is really simple.)
Is 'a' less than 10? YES (it's 0)
Make 'a' one larger (now 1)
print on-screen what 'a' is (1)

Is 'a' less than 10? YES (it's 1)
Make 'a' one larger (now 2)
print on-screen what 'a' is (2)

Is 'a' less than 10? YES (it's 2)
Make 'a' one larger (now 3)
print on-screen what 'a' is (3)

Is 'a' less than 10? YES (it's 3)
Make 'a' one larger (now 4)
print on-screen what 'a' is (4)

Is 'a' less than 10? YES (it's 4)
Make 'a' one larger (now 5)
print on-screen what 'a' is (5)

Is 'a' less than 10? YES (it's 5)
Make 'a' one larger (now 6)
print on-screen what 'a' is (6)

Is 'a' less than 10? YES (it's 6)
Make 'a' one larger (now 7)
print on-screen what 'a' is (7)

Is 'a' less than 10? YES (are you still here?)
Make 'a' one larger (now 8)
print on-screen what 'a' is (8)

Is 'a' less than 10? YES (it's 8)
Make 'a' one larger (now 9)
print on-screen what 'a' is (9)

Is 'a' less than 10? YES (it's 9)
Make 'a' one larger (now 10)
print on-screen what 'a' is (10)

Is 'a' less than 10? NO (it's 10, therefore isn't less than 10)
Don't do the loop
There's no code left to do, so the program ends.
So in short, try to think of it that way when you write while loops. This is how you write them, by the way:
Code Example 4 – while loop form
while {condition that the loop continues}:
    {what to do in the loop}
    {have it indented, usually four spaces}
{the code here is not looped}
{because it isn't indented}
An example:
Code Example 5 – while loop example
#EXAMPLE
#Type this in and see what it does.
x = 10
while x != 0:
    print x
    x = x - 1
    print "Wow, we've counted x down, and now it equals", x
print "And now the loop has ended."
                        Remember, to make a program, you open IDLE, click 'File > New Window', type your program in the new window, then press F5 to run.
Boolean Expressions (Boolean... what?!?)]
              What do you type in the area marked {conditions that the loop continues}? The answer is a boolean expression.
                                What? A forgotten concept for the non-math people here. Never mind, boolean expression just means a question that can be answered with a TRUE or FALSE response. For example, if you wanted to say your age is the same as the person next to you, you would type:
My age == the age of the person next to me
And the statement would be TRUE. If you were younger than the person opposite, you'd say:
My age < the age of the person opposite me
And the statement would be TRUE. If, however, you were to say the following, and the person opposite of you was younger than you:
My age < the age of the person opposite me
                                The statement would be FALSE - the truth is that it is the other way around. This is how a loop thinks - if the expression is true, keep looping. If it is false, don't loop. With this in mind, lets have a look at the operators (symbols that represent an action) that are involved in boolean expressions:
Table 1 - Boolean operators
Expression
Function
less than
<=
less that or equal to
greater than
>=
greater than or equal to
!=
not equal to
<> 
not equal to (alternate, != preferred)
==
equal to
                                Dont get '=' and '==' mixed up - the '=' operator makes what is on the left equal to what is on the right. the '==' operator says whether the thing on the left is the same as what is on the right, and returns true or false.
Conditional Statements:
                        OK! We've (hopefully) covered 'while' loops. Now let's look at something a little different - conditionals.
                Conditionals are where a section of code is only run if certain conditions are met. This is similar to the 'while' loop you just wrote, which only runs when x doesn't equal 0. However, Conditionals are only run once. The most common conditional in any program language, is the 'if' statement. Here is how it works:
Code Example 6 - if statement and example
'''
if {conditions to be met}:
    {do this}
    {and this}
    {and this}
{but this happens regardless}
{because it isn't indented}
'''

#EXAMPLE 1
y = 1
if y == 1:
    print "y still equals 1, I was just checking"

#EXAMPLE 2
print "We will show the even numbers up to 20"
n = 1
while n <= 20:
    n = n + 1
    if n % 2 == 0:   
           print n
print "there, done."
                                Example 2 there looks tricky. But all we have done is run an 'if' statement every time the 'while' loop runs. Remember that the % just means the remainder from a division - just checking that there is nothing left over if the number is divided by two - showing it is even. If it is even, it prints what 'n' is.
'else' and 'elif' - When it Ain't True
                There are many ways you can use the 'if' statement, to deal with situations where your boolean expression ends up FALSE. They are 'else' and 'elif'.
'else' simply tells the computer what to do if the conditions of 'if' aren't met. For example, read the following:
Code Example 7 - the else statement
a = 1
if a > 5:
    print "This shouldn't happen."
else:
    print "This should happen."
'a' is not greater than five, therefore what is under 'else' is done.
'elif' is just a shortened way of saying 'else if'. When the 'if' statement fails to be true, 'elif' will do what is under it IF the conditions are met. For example:
Code Example 8 - The elif statement
z = 4
if z > 70:
    print "Something is very wrong"
elif z < 7:
    print "This is normal"
The 'if' statement, along with 'else' and 'elif' follow this form:
Code Example 9 - the complete if syntax
if {conditions}:
    {run this code}
elif {conditions}:
    {run this code}
elif {conditions}:
    {run this code}
else:
    {run this code}

#You can have as many or as few elif statements as you need
#anywhere from zero to the sky.
#You can have at most one else statement
#and only after all other ifs and elifs.
                One of the most important points to remember is that you MUST have a colon (:) at the end of every line with an 'if', 'elif', 'else' or 'while' in it. I forgot that, and as a result a stack of people got stumped at this lesson (sorry ;)).
Indentation:
                  One other point is that the code to be executed if the conditions are met, MUST BE INDENTED. That means that if you want to loop the next five lines with a 'while' loop, you must put a set number of spaces at the beginning of each of the next five lines. This is good programming practice in any language, but python requires that you do it. Here is an example of both of the above points:
Code Example 10 - Indentation
a = 10
while a > 0:
    print a
    if a > 5:
        print "Big number!"
    elif a % 2 != 0:
        print "This is an odd number"
        print "It isn't greater than five, either"
    else:
        print "this number isn't greater than 5"
        print "nor is it odd"
        print "feeling special?"
    a = a - 1
    print "we just made 'a' one less than what it was!"
    print "and unless a is not greater than 0, we'll do the loop again."
print "well, it seems as if 'a' is now no bigger than 0!"
print "the loop is now over, and without furthur ado, so is this program!"
Notice the three levels of indents there:
                         Each line in the first level starts with no spaces. It is the main program, and will always execute. Each line in the second level starts with four spaces. When there is an 'if' or loop on the first level, everything on the second level after that will be looped/'ifed', until a new line starts back on the first level again. Each line in the third level starts with eight spaces. When there is an 'if' or loop on the second level, everything on the third level after that will be looped/'ifed', until a new line starts back on the second level again. This goes on infinitely, until the person writing the program has an internal brain explosion, and cannot understand anything he/she has written. There is another loop, called the 'for' loop, but we will cover that in a later lesson, after we have learnt about lists.