Software Engineers Handbook/Language Dictionary/Multi-paradigmed/Python

From Wikibooks, open books for an open world
Jump to: navigation, search

<Language Name Here>[edit]

Created by a Dutch programmer Guido Von Rossum , who had worked on ABC programming language, which itself derives from SETL programming language. ABC had indenting for syntax scoping and reading clarity, and SETL had list comprehensions and aimed for the clarity of set notation and theory.

Type[edit]

python is described as a scripting language, and is usually run interpreted, although the interpreter scans the entire source for parsing prior to execution, and will halt if a syntax or type error occurs, presumably when constructing a parse tree that has nodes with type restrictions on their children.

Execution Entry Point[edit]

The entry point is a scripting if-conditional at the leftmost code containing indentation, using the global variable __name__, and the looking for the value "__main__"

if __name__ == "__main__":
      #do program
      return

General Syntax[edit]

statements belonging to the same scope have the same indentation, and indentation is best done using spaces, usually 4 spaces per scope ( sometimes 2 is easier). There is no semi-colon statement separator like php, c, basic, pascal , c++, java , but there is a end colon to designate start of a conditional block , or loop block . variable types are inferred on assignment.

if __name__ == "__main__":
 
    # raw_input(prompt) is a built-in function , that returns a str
    answ = raw_input("How many names ? ")
 
    # convert the string into a usable integer
    n = int ( answ )
 
   #lists are assigned with square brackets,  dictionaries are assigned with curly brackets
 
   list = []
   m = { "salutation": "Hello World "  ,  "conclusion": "Bye" }
 
   #libraries are available in the same scope where imported, or child scopes
   import random
 
   #"for i in xrange(0,n)"  is like   "for i := 0 to n do" or  "for( i = 0; i <  n ; ++i)" in other languages  
   for i in xrange(0, n):
       #indentation at the same level belong to the closest lower indent scope, e.g."for" loop 
       name = raw_input("Enter a name #"+str(i) )
 
       if random.randint(0,1) == 0:
            list.append(name)
       else:
            # "extend([name])"  is the same as "append(name)"  here, 
            # except "[name]" could have been "[name, name1, name2]" 
            #which would add 3 names to the list
            list.extend( [name] )
 
    while True:
        print m["salutation"] , list
        str = raw_input("Keep going ?")
        if str == "n":
             #breaks out of the nearest enclosing loop statement
             break
 
     # a function is available in the same scope or higher
     def bye():
         print m["conclusion"]
 
     bye()

Comments[edit]

#this is a comment,
#that needs another
#hash to flow onto the
#next line.

Variable Declarations[edit]

Variables are declared when first assigned

#this is an error, 
#list not declared
for x in list:
     print x
 
#list is declared as an empty list by first assignment
list=[]
for x in list:
    print x

Method Declaration/Implementation[edit]

<Describe how methods/functions/procedures are declared and implemented.>

a function is declared with a "def" at the beginning, and a colon at the end , and the indented following statements are part of the function

m={ "val": "Mum" , "next": [] }
c = { "val": "Tommy" , "next": [] }
gc = { "val" : "Kelly", "next": [] }
gc2 = { "val" : "Liam", "next":[] }
 
def add_children( p, children):
    p['next'] .extend(children)
 
add_children(m, [c] )
add_children(c,  [gc, gc2] )
 
 
#recursively shows parent and children , depth first
# indent will default to 0 if omitted
 
def show_family( p, indent = 0 ):
     print indent * "  " , p['val']
     #recursion ends when p["next"] is an empty list
     for ch in p["next"]:
        show_family( ch, indent+1)
 
 
show_family( m)

Scope[edit]

<Describe how scope is defined.> statements belong to the functional scope of the closest lower indent. There is a unnamed global functional scope. Variables and functions declared in a functional scope, can't be accessed outside the function they are declared in.

print "I will always be printed"
a = 1
 
if __name__ == "__main__":
    print "I will also always be printed, and I can access a=", a
    b = 2
    def f():
           c = 1
 
    f()
def g():
       d = 2
       def h():
           e = d
           x = b
 
g()
 
 
print "I can  access b=",b , "because b belongs in a compound statement block of the same functional scope (global)"
print "and f() can also be called"
 
print "But c, d ,e and h()  can't be accessed "

Conditional Statements[edit]

<Describe the conditional statements in text and present

code examples. 

(put a space in the front of the line to format as code)>

Looping Statements[edit]

<Describe looping statements in English and present code examples.>

Output Statements[edit]

<Describe how to output Hello world! including the new-line with or without a carriage return.>

Error Handling/Recovery[edit]

<Describe error handling and recovery. Give examples as appropriate.>

Containers[edit]

<List containers or references to lists of containers available natively for this language. List ways to incorporate containers if they are not native to the language.>

Algorithms[edit]

<List algorithms or references to lists of algorithms available natively for this language. List ways to incorporate algorithms if they are not native to the language. Or, if not available, describe that.>

Garbage collection[edit]

<Describe whether the garbage collection is automatic or manual.>

Physical Structure[edit]

<Describe how the files, libararies, and parts are typically divided and arranged.>

Tips[edit]

<Please include tips that make it easier to switch to this language from another language.>

Web References[edit]

<List additional references on the web. Please include for what level reader the references are appropriate. (beginner/intermediate/advanced)>

Books and Articles[edit]

<List additional books and articles that may be helpful. Please include for what level reader the references are appropriate. (beginner/intermediate/advanced)>