Merge Vattam and KD branches.
authorSantosh G. Vattam <vattam.santosh@gmail.com>
Tue, 08 Sep 2009 18:45:51 +0530
changeset 51 960e67a7c45f
parent 50 0985027f4c8c (diff)
parent 45 9200c7887c57 (current diff)
child 52 9748190df418
Merge Vattam and KD branches.
--- a/basic_python/intro.rst	Tue Sep 08 18:15:00 2009 +0530
+++ b/basic_python/intro.rst	Tue Sep 08 18:45:51 2009 +0530
@@ -91,7 +91,8 @@
 appearance might differ based on the version of Python being used. The ``>>>``
 thing shown is the python prompt. When something is typed at the prompt and the
 enter key is hit, the python interpreter interprets the command entered and
-performs the appropriate action.
+performs the appropriate action. All the examples presented in this document are
+to be tried hands on, on the interactive interpreter.
 
 ::
 
@@ -196,6 +197,11 @@
   This example is to show that unlike in C or C++ there is no limit on the
   value of an integer.
 
+Try this on the interactive interpreter:
+``import this``
+
+*Hint: The output gives an idea of Power of Python*
+
 *ipython* - An enhanced interactive Python interpreter
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
@@ -277,7 +283,7 @@
     print gcd(72, 92)
 
 To run the script, open the shell prompt, navigate to the directory that 
-contains the python file and run `python <filename.py>` at the prompt ( in this 
+contains the python file and run ``python <filename.py>`` at the prompt ( in this 
 case filename is gcd.py )
 
 **Running the python script**
@@ -289,7 +295,7 @@
 
 Another method to run a python script would be to include the line
 
-`#! /usr/bin/python`
+``#! /usr/bin/python``
 
 at the beginning of the python file and then make the file executable by 
 
@@ -340,7 +346,7 @@
 The only distinction comes during type checking (which is not a healthy practice).
 Long numbers are tucked with a trailing 'L' just to signify that they are long.
 Notice that in the example just lng at the prompt displays the value of the variable
-with the 'L' whereas `print lng` displays without the 'L'. This is because print 
+with the 'L' whereas ``print lng`` displays without the 'L'. This is because print 
 formats the output before printing. Also in the example, notice that adding an 
 integer to a long does not give any errors and the result is as expected. So for
 all practical purposes longs can be treated as ints.
@@ -409,3 +415,278 @@
 Strings
 ~~~~~~~
 
+Strings are one of the essential data structures of any programming language.
+The ``print "Hello, World!"`` program was introduced in the earlier section, and
+the *"Hello, World!"* in the print statement is a string. A string is basically 
+a set of characters. Strings can be represented in various ways shown below:
+
+::
+
+  s = 'this is a string'              # a string variable can be represented using single quotes
+  s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown
+  s = "I have 'single-quotes' inside!"
+  l = "A string spanning many lines\
+  one more line\
+  yet another"                        # a string can span more than a single line.
+  t = """A triple quoted string does  # another way of representing multiline strings.
+  not need to be escaped at the end and
+  "can have nested quotes" etc."""
+
+Try the following on the interpreter:
+``s = 'this is a string with 'quotes' of similar kind'``
+
+**Exercise: How to use single quotes within single quotes in a string as shown 
+in the above example without getting an error?**
+
+String operations
+-----------------
+
+A few basic string operations are presented here. 
+
+**String concatenation**
+String concatenation is done by simple addition of two strings.
+
+::
+
+  >>> x = 'Hello'
+  >>> y = ' Python'
+  >>> print x+y
+  Hello Python
+
+*Try this yourself:*
+
+::
+  
+  >>> somenum = 13
+  >>> print x+somenum
+
+The problem with the above example is that here a string variable and an integer
+variable are trying to be concantenated. To obtain the desired result from the 
+above example the str(), repr() and the `` can be used.
+
+**str()** simply converts a value to a string in a reasonable form.
+**repr()** creates a string that is a representation of the value.
+
+The difference can be seen in the example shown below:
+
+::
+  
+  >>> str(1000000000000000000000000000000000000000000000000L)
+  '1000000000000000000000000000000000000000000000000'
+  >>> repr(1000000000000000000000000000000000000000000000000L)
+  '1000000000000000000000000000000000000000000000000L'
+
+It can be observed that the 'L' in the long value shown was omitted by str(), 
+whereas repr() converted that into a string too. An alternative way of using 
+repr(value) is ```value```. 
+
+A few more examples:
+::
+  
+  >>> x = "Let's go \nto Pycon"
+  >>> print x
+  Let's go 
+  to Pycon
+
+In the above example, notice that the '\n'(newline) character is formatted and 
+the string is printed on two lines. The strings discussed until now were normal 
+strings. Other than these there are two other types of strings namely, raw strings
+and unicode strings.
+
+**Raw strings** are strings which are unformatted, that is the backslashes(\) are 
+not parsed and are left as it is in the string. Raw strings are represented with
+an 'r' at the start of a string. 
+Let us look at an example
+
+::
+  
+  >>> x = r"Let's go \nto Pycon"
+  >>> print x
+  Let's go \nto Pycon
+
+Note: The '\n' is not being parsed into a new line and is left as it is.
+
+*Try this yourself:*
+
+::
+  
+  >>> x = r"Let's go to Pycon\"
+
+**Unicode strings** are strings where the characters are Unicode characters as 
+opposed to ASCII characters. Unicode strings are represented with a 'u' at the 
+start of the string.
+Let us look at an example:
+
+::
+  
+  >>> x = u"Let's go to Pycon!"
+  >>> print x
+  Let's go to Pycon!
+
+Boolean
+~~~~~~~
+
+Python also provides special Boolean datatype. A boolean variable can assume a 
+value of either *True* or *False* (Note the capitalizations). 
+
+Let us look at examples:
+
+::
+
+  >>> t = True
+  >>> f = not t
+  >>> print f
+  False
+  >>> f or t
+  True
+  >>> f and t
+  False
+
+The **while** loop
+~~~~~~~~~~~~~~~~~~
+
+The Python **while** loop is similar to the C/C++ while loop. The syntax is as
+follows:
+
+::
+
+  statement 0
+  while condition:
+    statement 1 #while block
+    statement 2 #while block
+  statement 3 #outside the while block.
+
+Let us look at an example:
+
+::
+
+    >>> x = 1  
+    >>> while x <= 5:
+    ...   print x
+    ...   x += 1
+    ... 
+    1
+    2
+    3
+    4
+    5
+
+The **if** conditional
+~~~~~~~~~~~~~~~~~~~~~~
+
+The Python **if** block provides the conditional execution of statements. 
+If the condition evaluates as true the block of statements defined under the if 
+block are executed.
+
+If the first block is not executed on account of the condition not being satisfied,
+the set of statements in the **else** block are executed.
+
+The **elif** block provides the functionality of evaluation of multiple conditions
+as shown in the example.
+
+The syntax is as follows:
+
+::
+
+  if condition :
+      statement_1
+      statement_2
+
+  elif condition:
+      statement_3
+      statement_4
+  else:
+      statement_5
+      statement_6
+
+Let us look at an example:
+
+::
+  
+   >>> n = raw_input("Input a number:")
+   >>> if n < 0:
+         print n," is negative"
+         elif n > 0:
+         print n," is positive"
+         else:
+         print n, " is 0"
+
+**raw_input()**
+~~~~~~~~~~~~~~~
+
+In the previous example we saw the call to the raw_input() subroutine. 
+The **raw_input()** method is used to take user inputs through the console.
+Unlike **input()** which assumes the data entered by the user as a standard python
+expression, **raw_input()** treats all the input data as raw data and converts
+everything into a string. To illustrate this let us look at an example.
+
+::
+
+  >>> input("Enter a number thats a palindrome:")
+  Enter a number thats a palindrome:121
+  121
+
+  >>> input("Enter your name:")
+  Enter your name:PythonFreak
+  Traceback (most recent call last):
+    File "<stdin>", line 1, in <module>
+    File "<string>", line 1, in <module>
+  NameError: name 'PythonFreak' is not defined
+
+As shown above the **input()** assumes that the data entered is a valid Python
+expression. In the first call it prompts for an integer input and when entered
+it accepts the integer as an integer, whereas in the second call, when the string
+is entered without the quotes, **input()** assumes that the entered data is a valid
+Python expression and hence it raises and exception saying PythonFreak is not 
+defined.
+
+::
+
+  >>> input("Enter your name:")
+  Enter your name:'PythonFreak'
+  'PythonFreak'
+  >>> 
+
+Here the name is accepted because its entered as a string (within quotes). But
+its unreasonable to go on using quotes each time a string is entered. Hence the
+alternative is to use **raw_input()**.
+
+Let us now look at how **raw_input()** operates with an example.
+
+::
+
+  >>> raw_input("Enter your name:")
+  Enter your name:PythonFreak
+  'PythonFreak'
+
+Observe that the **raw_input()** is converting it into a string all by itself.
+
+::
+
+  >>> pal = raw_input("Enter a number thats a palindrome:")
+  Enter a number thats a palindrome:121
+  '121'
+
+Observe that **raw_input()** is converting the integer 121 also to a string as 
+'121'. Let us look at another example:
+
+::
+  
+  >>> pal = raw_input("Enter a number thats a palindrome:")
+  Enter a number thats a palindrome:121
+  >>> pal + 2
+  Traceback (most recent call last):
+    File "<stdin>", line 1, in <module>
+  TypeError: cannot concatenate 'str' and 'int' objects
+  >>> pal
+  '121'
+
+Observe here that the variable *pal* is a string and hence integer operations
+cannot be performed on it. Hence the exception is raised.
+
+**int()** method
+~~~~~~~~~~~~~~~~
+
+Generally for computing purposes 
+
+Let us look at an example.