Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Important Python Notes, Study notes of Programming Languages

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. ... Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse.

Typology: Study notes

2019/2020

Available from 12/10/2021

doli-stark
doli-stark 🇮🇳

1 document

1 / 40

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Contents
Preface i
Contents 2
1 Getting Started 3
1.1 BasicSkills ................................ 4
1.1.1 Using xterms and logging in to the server . . . . . . . . . . . . 4
1.1.2 About the Python Shell and idle . . . . . . . . . . . . . . . . 5
1.1.3 Running Python Locally . . . . . . . . . . . . . . . . . . . . . 7
1.2 FunwithPython ............................. 8
1.2.1 Basicoperations ......................... 8
1.2.2 Lists, tuples and strings . . . . . . . . . . . . . . . . . . . . . 9
1.2.3 Modules .............................. 11
1.2.4 Gettinghelp............................ 11
1.2.5 Program control: Looping, conditionals and functions . . . . . 12
1.3 Progressing in Python . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.3.1 Writing your own modules and executable scripts . . . . . . . 17
1.3.2 List comprehension . . . . . . . . . . . . . . . . . . . . . . . . 18
1.3.3 Using objects in Python . . . . . . . . . . . . . . . . . . . . . 18
1.3.4 The Numeric arraypackage ................... 20
1.3.5 The Curve object and its uses . . . . . . . . . . . . . . . . . . 25
1.4 Advanced Python Topics . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.4.1 Defining your own objects . . . . . . . . . . . . . . . . . . . . 28
v
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28

Partial preview of the text

Download Important Python Notes and more Study notes Programming Languages in PDF only on Docsity!

Contents

12.5 Installing the courseware......................... 85

Chapter 1

Getting Started

1.1. BASIC SKILLS 5

issue Unix commands and log onto remote systems for text-based applications by issuing the ssh command in this window, the OSX terminal window does not handle graphics. Further, OSX does not come with the X windowing system installed by default. Fortunately, Appole provides an excellent implementation for X on OSX, which can be installed from the system install disk. If you have your own OSX Mac, or have administrative privileges for some OSX Mac you can use, you can install X11 yourself very easily. All Macs set up for this course should, in principle, already have X11 installed. To get an xterm, you just click on the X11 icon in the toolbar and wait for X to start up. The default windows X puts up on the screen are all xterms. You can make a window go away by typing ctrl-d in the window (meaning hold down the ctrl key and type d. If you want a new xterm, just type xterm& in any existing xterm window, or choose terminal from the Applications menu, and a new one will pop up. Your instructor can show you how to move and resize windows or turn them into icons.

Once you have an xterm on your screen, click the mouse in its window to activate it. You are now ready to log in to the course server. If you happen to be on a Unix workstation with the course data and software installed locally, you can just skip the login step. This is one of the beauties of X and Unix – the system doesn’t really care which computer is actually doing the calculation. This remark applies equally to OSX Macs, provided that Unix versions of the course software have been properly installed.

Now let’s assume that you need to log on to the course server. You’ll need an account to go further: a userid and a password. If you already have an account on climate, you can use that. If not,you can get one of the pre-assigned accounts from the TA. Once you have this data, you can log in. To log in, just issue the command ssh -X -l climate.myUniversity.edu from an xterm, where is the userid for the course account. Then give your password at the prompt. The -X option tells the server to forward graphical commands to the local X windowing system for handling. On many Linux systems, this option is turned on by default, but it never hurts to include it explicitly.

1.1.2 About the Python Shell and idle

Python is an interpreted language, which means you just type in plain text to an interpreter, and things happen. There is no compilation step, as in languages such as c or FORTRAN. To start up the Python interpreter,just type python from the command line on climate. You’ll get a prompt, and can start typing in python commands. Try typing in 2.5*3+5. and see what happens. To exit the Python interpreter, type ctrl-d.

6 CHAPTER 1. GETTING STARTED

Eventually, you’ll probably want to put your Python programs, or at least your function definitions, in a file you create and edit with a text editor, and then load it into Python later. This saves you having to re-type everything every time you run. The standard Unix implementation of Python provides an integrated development environment called idle, which bundles a Python interpreter window with a Python- aware text editor. To start up idle, log in to the server from an xterm and type IDLE. You will get a Python shell window, which is an ordinary Python interpreter except that it allows some limited editing capabilities. The real power of idle comes from the use of the integrated editor. To get an editor window for a new file, just choose New Window from the File menu on the Python Shell window. If you want to work with an existing file instead, just choose Open from the File menu, and pick the file you want from the resulting dialog box. You can type text into the editor window, and cut and paste in a fashion that will probably be familiar to most computer users. You can have as many editor windows open as you want, and cut and paste between them. When you are done with your changes, select Save or Save as from the File menu of the editor window, and respond to the resulting dialog box as necessary. Once you have saved a file, you can run it by selecting Run module from the Run menu.

You can actually use the integrated editor to edit just about any text file, but it has features that make it especially useful for Python files. For example, it colorizes Python key words, automatically indents in a sensible way, and provides popup advice windows that help you remember how various Python functions are used. As an exercise at this point, you should try creating and saving a short note (e.g. a letter of gratitude to your TA), and then try opening it up again in a new editor window. To exit from idle just choose Exit from the File menu of any window.

An especially useful feature of the idle editor is that it allows you to execute the Python script you are working on without leaving the window. To do this, just choose Run Script from the Edit menu of the editor window. Then the script will run in the Python shell window. When the script is done running, you can type additional Python commands into the shell window, to check the values of various quantities and so forth.

IDLE has various other powerful features, including debugging support. You can manage without these, but you should feel free to learn about and experiment with them as you go along.

Once you have written a working Python script and saved it,say, as MyScript.py, you can run it from the command line by typing python MyScript.py. There is no need to start up IDLE just to run a script.

8 CHAPTER 1. GETTING STARTED

1.2 Fun with Python

This is a very simple lab designed to help you get used to programming with Python. Throughout this and the rest of the Python labs, it is expected that you will try out all the examples in the Python interpreter window, and make up additional examples on your own until you feel you understand the concept being introduced. For the most part, you won’t be bothered with any further reminders of this expectation.

First, start up the Python interpreter. For this lab, you can type your input directly into the interpreter, if you wish. As you begin to do more complex programs, however, you will want to write your programs using a text editor, and then save them before running. This way, you won’t have to retype everything when you need to correct a mistake in just one or two lines, and you can re-run the program or a modification of it very easily. Although none of the exercises in this lab are complex enough to really require the text editor, you can use this lab as an opportunity to become familiar with the use of the idle editor.

1.2.1 Basic operations

Once you’re at the Python interpreter prompt, try some simple statements using Python like a calculator, e.g.:

a = 7. b=10. a/b ab a = 7 b = 10 ab a/b 2** 1717%

and so forth. This is so nice,you’ll probably want to load Python onto your laptop and use it in place of a pocket calculator, especiallly once you learn how to import the standard math functions into your Python world. These examples illustrate the use of floating point numbers, multiplication and addition (””, ”+” and ”/) assignment to variables, integers, and exponentiation ”*”. The final example illustrates the use of the ”mod” operator, % which is a binary operator applied to integers. The expression n%m yields an integer whose absolute value is less than m, which is the

1.2. FUN WITH PYTHON 9

result of subtracting off the maximum possible multiples of m (if you are familiar with clock arithmetic, this is the operation that turns regular arithmetic into clock arithmetic modulo m). The assignments to the variables a and b illustrate that Python is not a typed language. You do not have to declare the variables as being of a certain type before you use them. They are just names, which are used as long as necessary to refer to some value. This extends not just to numbers, but to all the object which Python can deal with, including arrays, lists, functions, strings and many other entities which will be introduced shortly. In the example above, first a and b are floats, and behave like floats on division. Then they are integers, and behave like integers. The last line illustrates the exponentiation operator, denoted by ”**”. The large number you get as a result has an ”L” tacked on the end, signifying that the result is a long integer, which can have arbitrarily many digits (until you run out of memory). Python automatically creates this type of integer whenever necessary. The standard Python floating point number has double precision, though Python extensions are available which allow you to specify arbitrary precision for floats as well.

Python also has floating point complex numbers as a native data type. A complex number with real and imaginary parts a and b respectively is written as a + bj. All the usual operations apply. After setting z = 7.5 + 4.j try z + 1, z ∗ z, 1 /z, z ∗ ∗ 1 .5 and z ∗ ∗z. If you need to make a complex number out of two real variables, say x and y, the easiest way is to use the complex function, e.g. z = complex(x,y). Python does not have complex integers (known as gaussian integers to mathematicians) as a native data type, but you will learn how to define these, and virtually any other specialized type you need, in Section 1.4.

1.2.2 Lists, tuples and strings

Tuples and lists are among the most basic and versatile data structures in Python. Lists contain any kind of data at all, and the elements can be of different types (floats, int, strings, even other tuples or lists). Many functions return tuples or lists. Try out the following examples in the interpreter

Heres an example showing two ways defining a list and getting at an element:

a = [1,’two’] a[0] a[1] b = [ ] b.append(1) b.append(’two’) b[0]

1.2. FUN WITH PYTHON 11

floats in scientific notation. There are other options to these format codes which give you more control over the appearance of the output, and also several additional format codes.

Now make up a few examples of your own and try them out.

1.2.3 Modules

To do almost any useful science with Python, you will need to load various libraries, known as ”modules.” Actually, a module can be just an ordinary Python script, which defines various functions and other things that are not provided by the core language. A module can also provide access to high-performance extensions written using compiled languages.

To make use of a module with name myModule, you just type: import myModule. Members of the module are accessed by prepending the module name to the member name, separated by a ”.”. For example, if myModule contains the constant r earth, and the function sza, these constant is accessed using myModule.r earth and the function is evaluated at t using myModule.sza(t). If you don’t need to keep the module’s members separate, you can avoid the need of prepending the module name by using from myModule import *.

The standard math functions are in the module math, and you make them avail- able by typing import math. To see what’s there, type dir(math); this works for any module. Now, to compute sin(π/ 7 .) for example, you type math.sin(math.pi/7.). To find out more about the function math.sin, just type help(math.sin). If you don’t like typing math.sin, you can import the module using from math import * instead, and then you can just use sin,cos, etc. without the prefix.

1.2.4 Getting help

Python has extensive built-in help functions, which make it possible to learn new things and avoid programming errors without frequent recourse to manuals. Given that so much of Python is found in various language extensions the Python commu- nity has written, the availability of embedded documentation is beholden to the good behavior of the programmer. Python fosters a culture of good behavior, and tries to make it easy for developers to provide ample help and documentation integrated with the tools they have developed.

The main ways of getting help in Python are the help() and dir() functions. For example, you have learned about the split() method that is one of the methods available to strings. Suppose you didn’t know what methods or data attributes went

12 CHAPTER 1. GETTING STARTED

along with a string, though? Rather than going to a handbook, you can use the dir() function to find out this sort of thing. For example, if a is a string, you can type dir(a) to get a list of all its methods, and also all its data attributes (e.g. its length). Then, if you want to know more about the split() method you can type help(a.split) (Warning: don’t type help(a.split()), which would look for help items on the words in the content of the string!). Both strings and lists have many useful and powerful methods attached to them. Many of these will be illustrated in the course of the examples given in the rest of this Workbook, but you are encouraged to explore them on your own, by finding out about them using dir() and help(), and then trying them out.

So when in doubt, try help and dir. One or the other will give you some useful information about just about anything in Python. If the system you are working on has the Python HTML documentation files installed, you can even get help on Python syntax and Python key words online. For example, to find out what the Python keyword for means, you just type help("for").

Further, since Python is interpreted rather than compiled into machine lan- guage, if you have some Python programs written by somebody else, you can almost always ”look under the hood” to see how they work. That is not generally possible with compiled languages where you often don’t have access to the original source code.

1.2.5 Program control: Looping, conditionals and functions

Now we’re ready for some more involved programming constructions. The basic technique for writing a loop is illustrated by the following example, which prints out the integers from 0 through 9:

for i in range(10): x = i*i print i,x

Note that in Python, indentation is part of the syntax. In the above example, the indentation is the only way Python has to identify the block of instructions that is being looped over. Indentation in a block of code must line up, and you need to be cautions not to confuse spaces and tabs. The use of indentation as a syntactic element in Python enforces code readability and reduces the need for special identifiers to terminate blocks.

The construct range(10) is actually shorthand for the 10-element list

[0,1,2,3,4,5,6,7,8,9]

14 CHAPTER 1. GETTING STARTED

An if block can have as many elif blocks as you need, and the conditional being tested can be anything that reasonably evaluates to a truth value. To distinguish from assignment, the equality relation is expressed by the symbol ==. The symbols <= and >= have the obvious meanings. The exclamation point negates a relation, and Python also provides the operator not to negate the truth value of an arbitrary logical expression. For example 1 != 0 and not (1 == 0) mean the same thing. Compound expressions can be built up from the Boolean operators for ”and” (&) and ”or” (|, the vertical bar). Python also provides the keywords True and False for logical values, but regular integers 1 and 0 generally do just as well in conditionals.

The organization of almost any program can benefit from the subdivision of the labor of the program into a number of functions. This makes the program easier to debug, since functions can be tested individually. It also allows the re-use of code that is needed in many different places in the program. The basic means of defining a function is illustrated in the following example, which returns the square of the argument:

def f(x): return x*x

From the command line, you would invoke this function, once it is defined, by typing, e.g. f(3).

Python can even handle recursion in functions. That is, functions can be defined in terms of themselves. As an example, a function to compute the factorial of n could be written:

def factorial(n): if n == 0: return 1 else: return n*factorial(n-1)

Functions can return multiple arguments, as in:

def powers(x): return x,xx,xx*x

This returns a tuple containing the three values. It can be very nicely used with Python’s ability to set multiple items to corresponding items of a tuple, using con- structions of the form:

x1,x2,x3 = powers(2)

1.2. FUN WITH PYTHON 15

Python functions work only on a copy of the arguments. It is important to keep this in mind, since it means that any changes made to these arguments (”side- effects”) do not affect the variable’s value in the calling program. Try this:

def f(myValue): myValue = 0

x = 1 print x f(x) print x

In this example, x is unchanged because functions work only on a local copy of their arguments. However, if the argument is a name which points to the location of some data, the data pointed to can be modified in the function. This may seem somewhat arcane, but the following simple example modifying an element in a list should illustrate the general principle:

def f(myList): myList[0] = myList[1]

L = [1,2,3,4,5]

f(L) print L

If you want to replace the list with a completely new list, based on the old one, the right way to do this is to return the new list, rather than doing anything to the argument:

def bump(myList): newList = [ ] for item in myList: newList.append(item+1) return newList

Then, if the user really intended to replace the old list, he or she would use L = bump(L)

Often, the evaluation of a function will require a number of constants or pa- rameters which you might not need to change very often, or which are common to a great many different functions. These could always be added to the parameter list. If there are many of them, that could become tedious. Soon you will learn how

1.3. PROGRESSING IN PYTHON 17

1.3.1 Writing your own modules and executable scripts

A module should be thought of as a library of useful definitions, including values of constants,lists, definitions of functions, objects,definition of object types, and what have you. A module can also contain executable commands of any type, which are executed by the interpreter when the module is imported. In fact, Python doesn’t make any real distinction between a module and any other executable script. Generally, you should think of modules as a place to store things that you will use repeatedly. Although you can execute a module any way that a Python script can usually be executed, a module is intended to be used by importing it into some other script that needs the entities defined by the module.

Generally, when developing code in Python, you always have an interpreter window open and an idle editor window. You try things out in the interpreter window, and if things work, you move things into the editor window, which you save for use as an executable script or as a module.

Let’s say that you’ve written a Python script and saved it as myModule.py. This script might execute a bunch of calculations, or it might just define functions that you want to use interactively from the Python command line, or it might do both. You can run this Python script from within the Python interpreter by typing import myModule. This will run all the executable statements, and also load any functions and so forth that you’ve defined in your file. This way of running is especially useful if you’ve defined a lot of nifty functions in your file, and then want to load them in so that you can try them out interactively in the interpreter. Note that all variables and functions imported in this way must be referred to with myModule. stuck on the beginning of it’s name. Thus, if your file had the statement radius = 6.0e6 in it, once you imported the file, you would use myModule.radius to get at the value of radius. Suppose now that you want to change the Python program you’ve just tried out. For example, you might want to change the definition of the radius to radius = 6.0e07. You can edit myModule.py in the editor window and save it, but to get the interpreter to recognize the changes, it doesn’t work to simply import it again. Instead, you need to type reload(myModule) into the interpreter.

You can import many different scripts into your Python interpreter session, and also use the import command in scripts you write yourself. Indeed, this is the way that extensions to Python are handled.

If you’ve written a script that performs some one task (e.g. making a plot of a temperature profile), it is not good practice to execute it by importing it as a module. Rather, you should save the file (say, myprog.py, then execute it from the command line by typing python myprog.py, or by loading it into an editor window

18 CHAPTER 1. GETTING STARTED

in idle and executing it from there.

1.3.2 List comprehension

List comprehension refers to the ability to create new lists by processing elements of old lists. It is one of the powerful features of Python that allows one to write compact, readable code, often doing without multiline loops. As a simple example, say we want to generate a list of 10 real numbers equally spaced by increments of

  1. Instead of writing a for loop and appending the values to a list, one can simply write [.1*i for i in range(10)]. Combined with the ability of Python to loop over any list at all, this is very versatile. For example, one can write [ f(.1) for f in [math.sin,math.cos,math.exp]]. Suppose we have an averaging function avg which returns the average of the elements of a list. Then, if L is a list of lists we want to average, we can create a list of average values by writing [avg(list) for list in L] The power of list comprehension is further enhanced by Python’s ability to do multiple assignments on a single line. For example, suppose we want to open three files, with names data0, data1, and data2. This can be done on a single line using

file0,file1,file2 = [open(name) for name in [’data%d’%i for i in range(3)] ]

The open statement which appears in this example is a built-in Python function that opens a file and returns a file object that can be used to read the contents of the file, or write new contents to the file.

1.3.3 Using objects in Python

An object is a collection of data and functions that act on the data. The functions in an object are known as methods Almost everything in Python is an object, and you have in fact working with many objects all along. For example, if mystring = "Use the force!", then when you split it using mystring.split() you are invoking the split method of a string object. The elements of an object are referenced by separating the name of the object from the element by a period, as in the string example. A function is called with parentheses, like any other function, and a value is simply referred to without parentheses. Objects can, if the designer so provides, do many other things. Objects can be called like functions. They can be indexed like lists or arrays (as in myobject[’frodo’], and they can even be used in arithmetic expressions.

The designer of an object does not actually define the object itself. The de- signer defines a class of objects. When you use an object, you create an instance