Wednesday, 20 February 2013

An Introduction to Python



Python

Python is a general purpose programming language that can be used effectively to build any kind of program. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
Click to download python


Literals

Python works by figuring out the meaning or value of some code. This is true for the tiniest pieces of code to the largest programs. The process of finding out the meaning of code is known as evaluation.
The things whose values are the things themselves are known as literals. The literals of Python can be categorized by the following types: integersrealnumbersstringsBooleans, and arrays.
Python (or more correctly, the Python interpreter) responds to literals by echoing back the literal itself. Here are examples of each of the types:
    >>> 3
    3
     
    >>> -4.9
    -4.9
     
    >>> "hello"
    'hello'

    >>>[3, -4.9, "hello"]
    [3, -4.9, 'hello']

Integers

Integers are numbers without any fractional parts. Examples of integers are:
    >>> 3
    3

Real Numbers

Reals are numbers that do have a fractional part (even if that fractional part is zero!). Examples of real numbers are:
    >>> 3.2
    3.2

Strings

Strings are sequences of characters delineated by double quotation marks:
    >>> "hello, world!"
    'hello, world!'
Python accepts both double quotes and single quotes to delineate strings.Characters in a string can be escaped (or quoted) with the backslash character, which changes the meaning of some characters. For example, the character n, in a string refers to the letter n while the character sequence \n refers to the newline character. A backslash also changes the meaning of the letter t, converting it into a tab character. You can also quote single and double quotes with backslashes. When other characters are escaped, it is assumed the backslash is a character of the string and it is escaped (with a backslash) in the result:
    >>> "\z"
    '\\z'
A string with no characters between the double quotes is known as an empty string.
Unlike some languages, there is no character type in Python. A single character a, for example, is entered as the string "a" or 'a'.

True, False, and None

There are two special literals, True and False. These literals are known as the Boolean values and are used to guide the flow of a program. The so-called Boolean logic or Boolean algebra is concerned with the rules of combining truth values (i.e., true or false).
Another special literal is None. This literal is used to indicate the end of lists; it also is used to indicate something that has not yet been created. 

Collections of literals

If you read any other text on Python, the basic way of grouping literals together (rather like throwing a bunch of groceries in a shopping bag) is called a list.
Arrays are just collections of values. One creates an array by enclosing a comma-separated listing of values in square brackets. The simplest array is empty:
    >>>[]
    []
Arrays can contain any values:
    >>>[2, "help", len]
    [2, 'help', <built-in function len>]
The first value is an integer, the second a string, and the third is something known as a function. We will learn more about functions later, but the len function is used to tell us how many items are in an array:
    >>> len([2, "help", len])
    3
Arrays can even contain arrays!
    >>>[0, [3, 2, 1] 4]
    [0, [3, 2, 1] 4]
An array is something known as a data structure; data structures are extremely important in writing sophisticated programs.

Indexing into Arrays

You can pull out an item from an array by using bracket notation. With bracket notation, you specify exactly which element (or elements) you wish to extract from the array. This specification is called an index. The first element of the array has index 0, the second index 1, and so on. Here is some code that extracts the first element of an array. Note that the first interaction creates a variable named items that points to an array of three elements.
    >>> items = ['a', True, 7]

    >>> items
    ['a', True, 7]

    >>> items[0]
    'a'

    >>> items[1]
    True
Extracting an item from an array leaves the array unchanged. What happens if our index is too large?
    >>> items[3]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      IndexError: list index out of range
There is a special notation for extracting more than one element of an array. This notation is known as a slice. Here is a slice that extracts all but the first element of an array:
    >>> items[1:]
    [True, 7]
This particular slice (you can slice an array many different ways) says, start extracting at the second item (which has index one) and go to the end. This operation is so common, it has a special name, taking the tail of an array.
Here is a slice that says, start extracting at the first element (which has index 0) and go up to, but do not include, the element with index 2:
    >>> items[0:2]
    ['a', True]

Operators

The operands of the other basic operators have special names too. For addition, the left operand is known as the augend and the right operand is known as theaddend. The result is known as the sum. For subtraction, the left operand is the minuend, the right the subtrahend, and the result as the difference. For division (and I think this is still taught), the left operand is the dividend, the right operand is the divisor, and the result is the quotient. Finally, for exponentiation, which is shorthand for repeated multiplication:
    >>> 3 ** 4
    81
    >>> 3 * 3 * 3 * 3
    81
the left operand is the base and the right operand is the exponent
If it makes sense to add two things together, you can probably do it in Python using the + operator. For example:
    >>> 2 + 3
    5
Adding an string to an integer (with an augend integer) yields an error; the types are not "close" enough, like they are with integers and reals:
    >>> 2 + "hello"
    TypeError: unsupported operand types(s) for +: 'int' and 'str'
In general, when adding two things, the types must match or nearly match.
>>> 1.9 + 3.1 5.0
One can see that if one adds two integers, the result is an integer.
You can even add strings with strings and arrays with arrays:
    >>> "hello" + "world"
    'helloworld'

    >>> [1, 3, 5] + [2, 4, 6]
    [1, 3, 5, 2, 4, 6]
You can multiply strings and arrays with numbers:
    >>> "hello" * 3
    'hellohellohello'

    >>> [1, 2] * 3
    [1, 2, 1, 2, 1, 2]
 The division operator with respect to integer operands. Consider evaluating the following expression:
    15 / 2
If one asked the Python interpreter to perform this task, the result would be 7.5, as expected. However, often we wish for just the quotient without the remainder. In this case, the quotient is 7 and the remainder is 0.5. The double forward slash operator is Python's quotient operator; if we ask the interpreter to evaluate
    14 // 5
the result would be 2, not 2.8. Use of the quotient operator is known as integer division.
The complement to integer division is the modulus operator %. While the result of integer division is the quotient, the result of the modulus operator is the remainder. Thus
    14 % 5
evaluates to 4 since 4 is left over when 5 is divided into 14. To check if this is true, one can ask the interpreter to evaluate:
    (14 // 5 * 5) + (14 % 5) == 14
This complicated expression asks the question "is it true that the quotient times the divisor plus the remainder is equal to the original dividend?". The Python interpreter will respond that, indeed, it is true. 

Comparing things

The Boolean literals, True and False can be used in the Boolean comparison operators to generate such values. For example, we can ask if 3 is less than 4:
    >>> 3 < 4
    True
Besides integers, we can compare reals with reals, strings with strings, and arrays with arrays using the comparison operators:
    >>> "apple" < "banana"
    True
    
    >>> [1, 2, 3] < [1, 2, 4]
    True
In general, it is illegal to compare integers or reals with strings.
>>> not(3 < 4 and 4 < 5)
    False
    
    >>> not(3 < 4 or 4 < 5)
    False

Precedence: 

+ and - have higher precedence than <The lowest precedence operator in Python is the assignment operator Next come the Boolean connectives and and or.  At the next higher level are the Boolean comparatives, <<=>>===, and !=.After that come the additive arithmetic operators + and-. Next comes the multiplicative operators */ and %. Higher still is the exponentiation operator **. Finally, at the highest level of precedence is the selection, or dot, operator (the dot operator is a period or full-stop). Higher precedence operations are performed before lower precedence operations. Functions which are called with operator syntax have the same precedence level as the mathematical operators.

Assignment and Arrays

You can change a particular element of a array by assigning a new value to the index of that element by using bracket notation:
    >>> items = ['a', True, 7]

    >>> items[0] = 'b'

No comments:

Post a Comment