Welcome to Python Programming Language Part 2. In this article we are briefing you all about the python programming language basics . The output from the chaos program may not look very exciting, but it illustrates a very interesting phenomenon known to physicists and mathematicians. Let’s take a look at this program line by line and see what it does. Don’t worry about understanding every detail right away; we will be returning to all of these ideas in the next chapter. The first two lines of the program start with the # character: # File: chaos.py # A simple program illustrating chaotic behavior. These lines are called comments. They are intended for human readers of the program and are ignored by Python. The Python interpreter always skips any text from the pound sign (#) through the end of a line. The next line of the program begins the definition of a function called main. def main(): Strictly speaking, it would not be necessary to create a main funct...
In last
article we saw all the technical details, it’s time to start having fun with
Python. In this article we will learn about python programming language basics. The ultimate goal is to make the computer do our bidding. To this end,
we will write programs that control the computational processes inside the
machine. You have already seen that there is no magic in this process, but in
some ways programming feels like magic. The computational processes inside the
computer are like magical spirits that we can harness for our work.
Unfortunately,
those spirits only understand a very arcane language that we do not know. What
we need is a friendly Genie that can direct the spirits to fulfill our wishes.
Our Genie is a Python interpreter. We can give instructions to the Python
interpreter, and it directs the underlying spirits to carry out our demands. We
communicate with the Genie through a special language of spells and
incantations (i.e., Python).
The best way
to start learning about Python is to let our Genie out of the bottle and try
some spells. You can start the Python interpreter in an interactive mode and
type in some commands to see what happens. When you first start the interpreter
program, you may see something like the following:
Python 2.1
(#1, Jun 21 2001, 11:39:00)
[GCC
pgcc-2.91.66 19990314 (egcs-1.1.2 release)] on linux2
Type
"copyright", "credits" or "license" for more
information. >>>
The
>>> is a Python prompt indicating that the Genie is waiting for us to
give it a command. In programming languages, a complete command is called a
statement. Here is a sample interaction with the Python interpreter.
>>>
print "Hello, World"
Hello, World
>>> print 2 + 3
5
>>> print "2 + 3 =", 2 + 3
2 + 3 = 5
Here I have
tried out three examples using the Python print statement. The first statement
asks Python to display the literal phrase Hello, World. Python responds on the
next line by printing the phrase.
The second print statement asks Python to
print the sum of 2 and 3. The third print combines these two ideas. Python
prints the part in quotes “2 + 3 =” followed by the result of adding 2 + 3,
which is 5. This kind of interaction is a great way to try out new things in
Python. Snippets of interactive sessions are sprinkled throughout this article.
When you see the Python prompt >>> in an example, that should tip you
off that an interactive session is being illustrated. It’s a good idea to fire
up Python and try the examples for yourself.
Usually we want to move beyond snippets and
execute an entire sequence of statements. Python lets us put a sequence of
statements together to create a brand-new command called a function. Here is an
example of creating a new function called hello.
>>>
def hello():
print
"Hello"
print
"Computers are Fun"
>>>
The first
line tells Python that we are defining a new function called hello. The
following lines are indented to show that they are part of the hello function.
The blank line (obtained by hitting the <Enter> key twice) lets Python
know that the definition is finished, and the interpreter responds with another
prompt. Notice that the definition did not cause anything to happen. We have
told Python what should happen when the hello function is used as a command; we
haven’t actually asked Python to perform it yet. A function is invoked by
typing its name. Here’s what happens when we use our hello command.
>>>
hello()
Hello
Computers
are Fun
>>>
Do you see
what this does? The two print statements from the hello function are executed
in sequence. You may be wondering about the parentheses in the definition and
use of hello. Commands can have changeable parts called parameters that are
placed within the parentheses. Let’s look at an example of a customized
greeting using a parameter. First the definition:
>>>
def greet(person):
print "Hello", person
print "How are you?"
Now we can
use our customized greeting.
>>>
greet("John")
Hello John How are you?
>>> greet("Emily")
Hello Emily How are you?
>>>
Can you see
what is happening here? When we use greet we can send different names to
customize the result. We will discuss parameters in detail later on. For the
time being, our functions will not use parameters, so the parentheses will be
empty, but you still need to include them when defining and using functions.
One problem
with entering functions interactively at the Python prompt like this is that
the definitions go away when we quit Python. If we want to use them again the
next time, we have to type them all over again. Programs are usually created by
typing definitions into a separate file called a module or script. This file is
saved on a disk so that it can be used over and over again.
A module file is just a text file, and you can
create one using any program for editing text, like a notepad or word processor
program (provided you save your program as a “plain text” file). A special type
of program known as a programming environment simplifies the process. A
programming environment is specifically designed to help programmers write
programs and includes features such as automatic indenting, colour
highlighting, and interactive development. The standard Python distribution
includes a programming environment called Idle that you may use for working on
the programs.
Let’s illustrate the use of a module file by
writing and running a complete program. Our program will illustrate a
mathematical concept known as chaos. Here is the program as we would type it
into Idle or some other editor and save in a module file:
# File:
chaos.py
# A simple
program illustrating chaotic behaviour.
def main():
print "This program illustrates a chaotic
function"
x = input("Enter a number between 0 and
1: ")
for i in
range(10):
x = 3.9 * x * (1 - x)
print x
main()
This file
should be saved with the name chaos.py. The .py extension indicates that this
is a Python module. You can see that this particular example contains lines to
define a new function called main. (Programs are often placed in a function
called main.) The last line of the file is the command to invoke this function.
Don’t worry if you don’t understand what main actually does; we will discuss it
in the next section. The point here is that once we have a program in a module
file, we can run it any time we want.
This program
can be run in a number of different ways that depend on the actual operating
system and programming environment that you are using. If you are using a
windowing system, you can run a Python program by double-clicking on the module
file’s icon. In a command-line situation, you might type a command like python
chaos.py. If you are using Idle (or another programming environment) you can
run a program by opening it in the editor and then selecting a command like
import, run, or execute. One method that should always work is to start the
Python interpreter and then import the file. Here is how that looks.
>>>
import chaos
This program illustrates a chaotic function
Enter a number between 0 and 1: .25
0.73125
0.76644140625
0.698135010439
0.82189581879
0.570894019197
0.955398748364
0.166186721954
0.540417912062
0.9686289303
0.118509010176
>>>
Typing the
first line import chaos tells the Python interpreter to load the chaos module
from the file chaos.py into main memory. Notice that I did not include the .py
extension on the import line; Python assumes the module will have a .py
extension.
As Python imports the module file, each line
executes. It’s just as if we had typed them one-by-one at the interactive
Python prompt. The def in the module causes Python to create the main function.
When Python encounters the last line of the module, the main function is
invoked, thus running our program. The running program asks the user to enter a
number between 0 and 1 (in this case, I typed “.25”) and then prints out a
series of 10 numbers.
When you
first import a module file in this way, Python creates a companion file with a
.pyc extension. In this example, Python creates another file on the disk called
chaos.pyc. This is an intermediate file used by the Python interpreter.
Technically, Python uses a hybrid compiling/interpreting process. The Python
source in the module file is compiled into more primitive instructions called
byte code. This byte code (the .pyc) file is then interpreted. Having a .pyc file
available makes importing a module faster the second time around. However, you
may delete the byte code files if you wish to save disk space; Python will
automatically re-create them as needed.
A module only needs to be imported into a
session once. After the module has been loaded, we can run the program again by
asking Python to execute the main command. We do this by using a special dot
notation. Typing chaos.main() tells Python to invoke the main function in the
chaos module. Continuing with our example, here is how it looks when we rerun
the program with 26 as the input.
>>>
chaos.main()
Enter a
number between 0 and 1:.26
0.75036
0.73054749456
0.767706625733
0.6954993339
0.825942040734
0.560670965721
0.960644232282
0.147446875935
0.490254549376
0.974629602149
>>>
Comments
Post a Comment