User Tools

Site Tools


software_carpentary3

This is an old revision of the document!


Python --- Interpreted Programming Language!!!

>>>Authors = [Medhamsh, [email protected]](Mail suggestions, typos please)

Interpreted –???

  • The instructions are executed immediately after parsing
  • Relative ease of programming (since once you type your instructions into a text file, the interpreter can run it) and no linker is required
  • Interpreted languages also tend to be more portable, able to be run without being modified for different computing environments
  • Suited for ad hoc requests or even for prototyping an application

Starting Python

Type 'python' at your shell and that should take you to the screen like this:

medhamsh@myhost:~$python

Python 2.7.2 (default, Jun 12 2011, 03:11:18) 
[GCC 4.6.0 20110603 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

That ">>>" is called a “prompt”, which means it’s something the computer displays to tell you it’s ready for your instructions. You can type things into that window, and the computer will obey them.

Python Calculator

What if we want to find out the sum of two and three?
Try the following at your python shell!

>>> Tell me the sum of two and three

Unfortunately the computer does not understand english! And we have to talk to it in special language. That special language here being python, fortunately is pretty easy for humans as well!!!

So, try it out like this: Type 2+3 and hit enter.

>>> 2+3
5
>>> 

As python is an interpreted programming language, you will have the results as you just hit on enter. Try various mathematical calculations.

  • Use + for addition
  • Use - for subtraction
  • Use * for multiplication (Not X)
  • Use / for division

Try using python as your pocket calculator!

Now try this. 1+2*3-4

>>> 1+2*3-4
3
>>> 

Is that what you expected? If you expected 5, try getting the output. You can use all sorts of paranthesis.

>>> (3+4)*(4+7)
77
>>> 

Incidentally, if you’re still confused about the fact that 1+2*3-4 gives 3 and not 5, the reason is that “multiplication happens before addition”. Your maths teacher at school probably calls this BODMAS or something similar.

Now, try this. 8/6

>>> 8/6
1
>>>

Did you expect it to be 1.3333333? Then you should try it like this: 8.0/6.0

>>> 8.0/6.0
1.3333333333333333
>>> 

Did you see the magical output?
This is how python treats numbers and how mathematical operations are performed.
Don’t be afraid to experiment. Whenever you learn something new that you can do with Python, try making slight changes (or bigger changes!) and play around until you’re confident that you understand just what’s going on. Don’t limit yourself to what’s actually printed here.

Objects

Till now we have played with python as your pocket calculator. Apart from that python can handle many things.
For Instance: Lets consider the hello world program.

>>> 'hello, ' + 'world'
'hello, world'
>>> 

Things between quotation marks are called “strings”. As you might guess from the lines above, you can apply + to strings as well as to numbers. It “concatenates” strings; that is, puts one immediately after the other.

Try this: 3 * 'hella '

>>>3*'hella '
'hella hella hella '
>>> 

You can surround strings in either single quotes or double quotes; Python doesn’t mind.

>>>'Doll' + "ar"
Dollar
>>>

Why would this(' , “) all matter?? Try printing: I'm Sorry!

Naming things

Giving names to things!

Suppose you know that you’re going to need to do a lot of calculations involving the number 123456. (Maybe it’s your annual salary in pounds, or something.) You could just type the number in every time:

>>> 123456*3
370368
>>> 123456/6
20576
>>> 123456-1000
122456

This might get very boring after a while. And if anyone else wanted to read what you were doing, they might be confused by the mysterious number 123456 and wonder why it appeared so often. We can solve either of these problems by giving the number a name. To save typing, give it a short name, like n (short for “number”, maybe). To make it more obvious what it means, give it a longer name, like salary. Here’s how we do that.

>>> salary=123456
>>> salary*4
493824
>>> salary/12
10288
>>> salary
123456

What we’ve called “names”, most people call “variables”. You’ll find out later why they’re called that.For now, “names” is fine.

Lists

Python also has lists!

Simple Lists

[1,2,3]

>>> [1,2,3]+[7,8]
[1, 2, 3, 7, 8]
>>> 

Methods of Lists

  • list.append(x): Add an item to the end of the list
  • list.extend(L): Extend the list by appending all the items in the given list
  • list.insert(i, x): Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list
  • list.remove(x): Remove the first item from the list whose value is x. It is an error if there is no such item
  • list.pop([i]): Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list
  • list.index(x): Return the index in the list of the first item whose value is x. It is an error if there is no such item
  • list.count(x): Return the number of times x appears in the list
  • list.sort(): Sort the items of the list, in place
  • list.reverse(): Reverse the elements of the list, in place

Lists as stack

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

Doing something Over and Over Again

So far we have done what your pocke calculator could do in math. Here's something your pocket calculator isn't so good at:

>>> for x in 1,2,3,4,5:
...    print x,x*x
...

The prompt changes to ... from >>>.It tells you that Python is expecting more. Just press Enter.

This is basically what people call as a 'for loop'.

Lists of lists of lists of...

Sometimes one list isn’t enough. Suppose you wanted to keep a list of what you had eaten for breakfast; it’s easy enough to write

>>> breakfast = [’idly’, ’puri’, ’dosa’, ’chapathi’]

and carry on. But suppose you wanted to list what you had eaten for breakfast every day, and you don’t always eat the same thing. What would we do?

Fortunately, Python is very helpful about this. Remember that we said earlier that lists were just collections of things. Well, lists are things too, so making lists of lists is just like making lists of anything else!

>>>breakfast = [
...   'Monday', ['idly', 'coffee'],
...   'Tuesday', ['dosa', 'juice', 'chutney'],
...   'Wednesday', ['coffee'] ]
>>> breakfast[3]
['dosa', 'juice', 'chutney']
>>> breakfast[1]
['idly', 'coffee']
>>> breakfast[0]
'Monday'
>>> breakfast[4]
'Wednesday'

Observed what happened? Try several things like that! Numbers in the square brackets indicate the indices.

Some people call lists of lists “2-dimensional arrays” or “tables”, because you can write them out in rows and columns (two dimensions!) like a table. Unlike real tables (and many other computer languages), in Python you don’t have to have every row the same length.

Regular Expressions

Finding and matching strings.

Use Cases:

  • Adding a period(full stop) at the end of 100 lines in a file.
  • Finding and replacing certain word with another word.(Hello with Hi)
  • Changing Rs. to $ in several occurances.

Implementation

  • Editors
  • Vi
  • Emacs
  • gedit
  • Programming Languages
  • Perl
  • Bash Scripts
  • Ruby
  • Unix Command Line
  • rename
  • grep
  • find
  • sed
  • Others
  • Syntax Highliting
  • Search Engine(Google)

Pattern Matching

'.' matches with any character '*' repeats the previous expression zero or more times

Metacharacters

a. matches with as, ab, arch etc
^ matches the begining of a line
$ matches end of a line
| alternation eg. H|h matches h or H
() grouping eg. H|hello matches H or hello
(H|h)ello matches Hello or hello
\ escapes any meta character
Mr. matches Mr. and Mrs.
Mr\. matches only Mr.

Character Classes

  • [Hh] means (h|H)
  • [0-9] means (0|1|2|3|4|5|6|7|8|9)
  • [0-9a-z] means ([0-9]|[a-z])
  • [^ab] matches any characters but not a and b
  • \x{0915} matches devanagari क
  • \n matches a new line
  • \r matches a return
  • \t matches a tab
software_carpentary3.1308576033.txt.gz · Last modified: 2018/03/24 11:13 (external edit)