Python Basics
(Learn Python Programming in 20 Minutes)
2 Getting started
2 Getting started
2.1 Running Python as a calculator
2.1 Running Python as a calculator
The easiest way to get started is to run Python as an
interpreter, which behaves similar to the way one would use a calculator. In
the interpreter, you type a command, and Python produces the answer. Then you
type another command, which again produes an answer, and so on. In OS X or
Linux, to start the Python interpreter is as simple as typing the command
python on the command line in a terminal shell. In Windows, assuming that
Python has already been installed, you need to find
Python in the appropriate menu. Windows users may choose to run Python in a
command shell (i.e., a DOS window) where it will behave very similarly to Linux
or OS X.
For all three operating systems (Linux, OS X, Windows)
there is also an integrated development environment for Python named IDLE. If
interested, you may download and install this on your computer.2 For help on
getting started with IDLE see http://hkn.eecs.berkeley.edu/~dyoo/python/idle_int
Once Python starts running in interpreter mode, using
IDLE or a command shell, it produces a prompt, which waits for your input. For
example, this is what I get when I start Python in a command shell on my Linux
box:
doty@brauer:~% python
Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu
4.2.3-2ubuntu7)] on linux2
Type
"help", "copyright", "credits" or
"license" for more information.
>>>
where the three symbols >>> indicates the prompt
awaiting my input.
So experiment,
using the Python interpreter as a calculator. Be assured that you cannot harm
anything, so play with Python as much as you like. For example:
>>> 2*1024
2048
>>> 3+4+9
16
>>> 2**100 1267650600228229401496703205376L
In the above, we first
asked for the product of 2 and 1024, then we asked for the sum of 3, 4, and 9
and finally
we asked for the value of 2100. Note that multiplication in Python
is represented by ∗,
addition by +, and exponents by **; you will need to remember this syntax. The
L appended to the last answer is there to indicate that this is a long integer;
more on this later. It is also worth noting that Python does arbitrary
precision integer arithmetic, by default:
>>> 2**1000
1071508607186267320948425049060001810561404811705533607443750
3883703510511249361224931983788156958581275946729175531468251
8714528569231404359845775746985748039345677748242309854210746
0506237114187795418215304647498358194126739876755916554394607
7062914571196477686542167660429831652624386837205668069376L
Here is another example, where we print a table of
perfect squares:
>>> for n in [1,2,3,4,5,6]:
... print n**2
...
1
4
9
1
6
25
36
This illustrates several points. First, the expression
[1,2,3,4,5,6] is a list, and we print the values of n2 for n varying
over the list. If we prefer, we can print horizontally instead of vertically:
>>> for n in [1,2,3,4,5,6]:
... print n**2,
...
1 4 9 16 25 36
simply by adding a comma at the end of the print command,
which tells Python not to move to a new line before the next print.
These last two examples are examples of a compound
command, where the command is divided over two lines (or more). That is why you
see ... on the second line instead of the usual >>>, which is the
interpreter’s way of telling us it awaits the rest of the command. On the third
line we entered nothing, in order to tell the interpreter that the command was
complete at the second line. Also notice the colon at the end of the first
line, and the indentation in the second line. Both are required in compound
Python commands.
2.2 Quitting the interpreter
In a terminal you can quit a Python session by CTRL-D.
(Hold down the CTRL key while pressing the D key.) In IDLE you can also quit
from the menu.
If the interpreter gets stuck in an infinite
loop, you can quit the current execution by CTRL-C.
2.3 Loading commands from the library
Python has a very extensive library of commands,
documented in the Python Library Reference Manual [2]. These commands
are organized into modules. One of the available modules is especially
useful for us: the math module. Let’s see how it may be used.
>>> from math import sqrt, exp
>>> exp(-1)
0.36787944117144233
>>> sqrt(2)
1.4142135623730951
We first import the sqrt and exp
functions from the math module, then use them to compute e−1 =
1/e
and √2.
Once we have loaded a function from a module, it is
available for the rest of that session. When we start a new session, we have to
reload the function if we need it.
Note that we could have loaded both functions sqrt and
exp by using a wildcard *:
>>> from math import *
which tells Python to import all the functions in
the math module.
What would have happened if we forgot to import a needed
function? After starting a new session, if we type
>>> sqrt(2)
Traceback (most recent call last):
File "<stdin >", line 1, in
<module>
NameError: name ’sqrt’ is not defined
we see an example of an error message, telling us that
Python does not recognize sqrt.
2.4 Defining functions
It is possible, and very useful, to define
our own functions in Python. Generally speaking, if you need to do a
calculation only once, then use the interpreter. But when you or others have
need to perform a certain type of calculation many times, then define a
function. For a simple example, the compound command
>>> def f(x):
... return x*x
...
defines the squaring function
f(x) = x2, a popular example used in elementary math courses. In the
definition,
the first
line is the function header where the name, f, of the function is specified.
Subsequent lines give the body of the function, where the output value is
calculated. Note that the final step is to return the
answer; without it we would never see any results. Continuing the example, we
can use the function to calculate the square of any given input:
>>> f(2)
4
>>> f(2.5)
6.25
The name of a function is purely arbitrary. We could have
defined
the same function as above, but with the name square instead of f; then to use
it we use the new function name instead of the old:
>>> def square(x):
... return x*x
...
>>> square(3)
9
>>> square (2.5)
6.25
Actually, a function name is not completely arbitrary,
since we are not allowed to use a reserved word as a function name.
Python’s reserved words are: and, def, del, for, is, raise, assert, elif, from, lambda, return,
break, else, global, not, try, class, except, if, or, while, continue, exec,
import, pass, yield.
By the way, Python also allows us to define
functions using a format similar to the Lambda Calculus in mathematical
logic. For instance, the above function could alternatively be defined
in the following way:
>>> square = lambda x: x*x
Here lambda x: x*x
is known as a lambda expression. Lambda expressions are useful when you need to
define a
function in just one line; they are also useful in situations where you need a
function but don’t want to name it.
Usually function definitions
will be stored in a module (file) for later use. These are
indistinguishable from Python’s Library modules from the user’s perspective.
2.5 Files
Python allows us to store our code in files
(also called modules). This is very useful for more serious programming, where
we do not want to retype a long function definition
from the very beginning just to change one mistake. In doing this, we are
essentially defining our own modules, just like the
modules defined already in the Python library. For
example, to store our squaring function example in a file,
we can use any text editor3 to type the code into a file,
such as
def square(x):
return x*x
Notice that we omit the prompt symbols >>>, ...
when typing the code into a file, but the indentation is
still important. Let’s save this file
under the name “SquaringFunction.py” and then open a terminal in order to run
it:
doty@brauer:~% python
Python 2.5.2 (r252:60911, Apr 21 2008,
11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on
linux2
Type "help",
"copyright", "credits" or "license"
for more information.
>>> from SquaringFunction
import square
>>> square (1.5)
2.25
Notice that I had to import the function from the file
before I could use it. Importing a command from a file
works exactly the same as for library modules. (In fact, some people refer to
Python files
as “modules” because of this analogy.) Also notice that the file’s
extension (.py) is omitted in the import command.
2.6 Testing code
As indicated above, code is usually developed in a file using
an editor. To test the code, import it into a Python session and try to run it.
Usually there is an error, so you go back to the file,
make a correction, and test again. This process is repeated until you are satisfied
that the code works. The entire process is known as the development cycle.
There are two types of errors that you will encounter. Syntax
errors occur when the form of some command is invalid. This happens when you
make typing errors such as misspellings, or call something by the wrong name,
and for many other reasons. Python will always give an error message for a
syntax error.
2.7 Scripts
If you use Mac OS X or some other variant of Unix (such
as Linux) then you may be interested in running Python commands as a script.
Here’s an example. Use an editor to create a file
name SayHi containing the following lines
#! /usr/bin/python
print "Hello World!"
print "- From your friendly Python program"
The first line tells Python that
this is a script. After saving the file,
make it executable by typing chmod 755
SayHi in the terminal. To run the script, type ./SayHi in the terminal. Note
that if you move the script someplace in your search path, then you can run it
simply by typing SayHi. Type echo $PATH to
see what folders are in your search path, and type which python to see where
your python program is — this should match the first
line in your script.
As far as I know, it is impossible to run Python scripts
in a similar way on a Windows machine.
1071508607186267320948425049060001810561404811705533607443750 3883703510511249361224931983788156958581275946729175531468251 8714528569231404359845775746985748039345677748242309854210746 0506237114187795418215304647498358194126739876755916554394607 7062914571196477686542167660429831652624386837205668069376L
This illustrates several points. First, the expression
[1,2,3,4,5,6] is a list, and we print the values of n2 for n varying
over the list. If we prefer, we can print horizontally instead of vertically:
>>> for n in [1,2,3,4,5,6]:
... print n**2,
...
1 4 9 16 25 36
simply by adding a comma at the end of the print command,
which tells Python not to move to a new line before the next print.
These last two examples are examples of a compound
command, where the command is divided over two lines (or more). That is why you
see ... on the second line instead of the usual >>>, which is the
interpreter’s way of telling us it awaits the rest of the command. On the third
line we entered nothing, in order to tell the interpreter that the command was
complete at the second line. Also notice the colon at the end of the first
line, and the indentation in the second line. Both are required in compound
Python commands.
2.2 Quitting the interpreter
2.2 Quitting the interpreter
In a terminal you can quit a Python session by CTRL-D.
(Hold down the CTRL key while pressing the D key.) In IDLE you can also quit
from the menu.
If the interpreter gets stuck in an infinite
loop, you can quit the current execution by CTRL-C.
2.3 Loading commands from the library
2.3 Loading commands from the library
Python has a very extensive library of commands,
documented in the Python Library Reference Manual [2]. These commands
are organized into modules. One of the available modules is especially
useful for us: the math module. Let’s see how it may be used.
>>> from math import sqrt, exp
>>> exp(-1)
0.36787944117144233
>>> sqrt(2)
1.4142135623730951
We first import the sqrt and exp
functions from the math module, then use them to compute e−1 =
1/e
and √2.
Once we have loaded a function from a module, it is
available for the rest of that session. When we start a new session, we have to
reload the function if we need it.
Note that we could have loaded both functions sqrt and
exp by using a wildcard *:
>>> from math import *
which tells Python to import all the functions in
the math module.
What would have happened if we forgot to import a needed
function? After starting a new session, if we type
>>> sqrt(2)
Traceback (most recent call last):
File "<stdin >", line 1, in
<module>
NameError: name ’sqrt’ is not defined
we see an example of an error message, telling us that
Python does not recognize sqrt.
2.4 Defining functions
It is possible, and very useful, to define
our own functions in Python. Generally speaking, if you need to do a
calculation only once, then use the interpreter. But when you or others have
need to perform a certain type of calculation many times, then define a
function. For a simple example, the compound command
>>> def f(x):
... return x*x
...
defines the squaring function
f(x) = x2, a popular example used in elementary math courses. In the
definition,
the first
line is the function header where the name, f, of the function is specified.
Subsequent lines give the body of the function, where the output value is
calculated. Note that the final step is to return the
answer; without it we would never see any results. Continuing the example, we
can use the function to calculate the square of any given input:
>>> f(2)
4
>>> f(2.5)
6.25
The name of a function is purely arbitrary. We could have
defined
the same function as above, but with the name square instead of f; then to use
it we use the new function name instead of the old:
>>> def square(x):
... return x*x
...
>>> square(3)
9
>>> square (2.5)
6.25
Actually, a function name is not completely arbitrary,
since we are not allowed to use a reserved word as a function name.
Python’s reserved words are: and, def, del, for, is, raise, assert, elif, from, lambda, return,
break, else, global, not, try, class, except, if, or, while, continue, exec,
import, pass, yield.
By the way, Python also allows us to define
functions using a format similar to the Lambda Calculus in mathematical
logic. For instance, the above function could alternatively be defined
in the following way:
>>> square = lambda x: x*x
Here lambda x: x*x
is known as a lambda expression. Lambda expressions are useful when you need to
define a
function in just one line; they are also useful in situations where you need a
function but don’t want to name it.
Usually function definitions
will be stored in a module (file) for later use. These are
indistinguishable from Python’s Library modules from the user’s perspective.
2.5 Files
Python allows us to store our code in files
(also called modules). This is very useful for more serious programming, where
we do not want to retype a long function definition
from the very beginning just to change one mistake. In doing this, we are
essentially defining our own modules, just like the
modules defined already in the Python library. For
example, to store our squaring function example in a file,
we can use any text editor3 to type the code into a file,
such as
def square(x):
return x*x
Notice that we omit the prompt symbols >>>, ...
when typing the code into a file, but the indentation is
still important. Let’s save this file
under the name “SquaringFunction.py” and then open a terminal in order to run
it:
doty@brauer:~% python
Python 2.5.2 (r252:60911, Apr 21 2008,
11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on
linux2
Type "help",
"copyright", "credits" or "license"
for more information.
>>> from SquaringFunction
import square
>>> square (1.5)
2.25
Notice that I had to import the function from the file
before I could use it. Importing a command from a file
works exactly the same as for library modules. (In fact, some people refer to
Python files
as “modules” because of this analogy.) Also notice that the file’s
extension (.py) is omitted in the import command.
2.6 Testing code
As indicated above, code is usually developed in a file using
an editor. To test the code, import it into a Python session and try to run it.
Usually there is an error, so you go back to the file,
make a correction, and test again. This process is repeated until you are satisfied
that the code works. The entire process is known as the development cycle.
There are two types of errors that you will encounter. Syntax
errors occur when the form of some command is invalid. This happens when you
make typing errors such as misspellings, or call something by the wrong name,
and for many other reasons. Python will always give an error message for a
syntax error.
2.7 Scripts
If you use Mac OS X or some other variant of Unix (such
as Linux) then you may be interested in running Python commands as a script.
Here’s an example. Use an editor to create a file
name SayHi containing the following lines
#! /usr/bin/python
print "Hello World!"
print "- From your friendly Python program"
The first line tells Python that
this is a script. After saving the file,
make it executable by typing chmod 755
SayHi in the terminal. To run the script, type ./SayHi in the terminal. Note
that if you move the script someplace in your search path, then you can run it
simply by typing SayHi. Type echo $PATH to
see what folders are in your search path, and type which python to see where
your python program is — this should match the first
line in your script.
As far as I know, it is impossible to run Python scripts
in a similar way on a Windows machine.
Verymuch usefull to all
ReplyDeleteThanks for the awesome review, We work hard to meet expectations like yours, and we’re happy to hear we hit the mark for you. Come back and see us soon. Cheers!
ReplyDelete