C463 B551Artificial IntelligenceC463 B551Artificial Intelligence
Dana VrajitoruDana Vrajitoru
PythonPython
Python IntroductionPython Introduction
An interpreted, compiled, and interactive, object-oriented, dynamic, imperative, and open sourceprogramming language.An interpreted, compiled, and interactive, object-oriented, dynamic, imperative, and open sourceprogramming language.
Created in early 90's by Guido von Rossum at StichtingMathematisch Centrum in the Netherlands.Created in early 90's by Guido von Rossum at StichtingMathematisch Centrum in the Netherlands.
The name comes from the Monty Python and not fromthe snake.The name comes from the Monty Python and not fromthe snake.
There is big community of Python programmers, withconferences and magazines:http://pycon.org/There is big community of Python programmers, withconferences and magazines:http://pycon.org/
Web site: www.python.org.Web site: www.python.org.
Features of PythonFeatures of Python
Interactive: one can launch Python console and runinstructions directly it.Interactive: one can launch Python console and runinstructions directly it.
Portable: available on most existing systems. It onlyrequires compiler to be ported to any new platform.Portable: available on most existing systems. It onlyrequires compiler to be ported to any new platform.
Structure: functions, classes, modules.Structure: functions, classes, modules.
It is easy to embed Python with C and C++.It is easy to embed Python with C and C++.
The user can write their own code in or C++ andcompile it as Python modules or functions. That makesPython extensible.The user can write their own code in or C++ andcompile it as Python modules or functions. That makesPython extensible.
Usual applications: scripts including CGI scripts, GUIs,scientific computing.Usual applications: scripts including CGI scripts, GUIs,scientific computing.
Many existing libraries for all sort of purposes.Many existing libraries for all sort of purposes.
Syntax RulesSyntax Rules
The syntax is designed to be simplified as compared toother languages like C/C++.The syntax is designed to be simplified as compared toother languages like C/C++.
Every compound instruction ends with ":"Every compound instruction ends with ":"
There are no blocks of code; blocks are implicitly createdby indentation.There are no blocks of code; blocks are implicitly createdby indentation.
Expressions: usual arithmetic operators, named logicoperators: and, or, not.Expressions: usual arithmetic operators, named logicoperators: and, or, not.
Assignments use the sign but they don't have to endwith ";"Assignments use the sign but they don't have to endwith ";"
Comments start with as in shell scripting.Comments start with as in shell scripting.
Variables are declared by assigning them value andthey are local to the block where they appear first.Variables are declared by assigning them value andthey are local to the block where they appear first.
Control StructuresControl Structures
Conditional:if condition:    instructionselif condition: #*    instructionselseoptional    instructionsConditional:if condition:    instructionselif condition: #*    instructionselseoptional    instructions
Loops:Loops:
while condition:    instructionswhile condition:    instructions
else:  optional    instructionselse:  optional    instructions
for var in S:           instructionsfor var in S:           instructions
else:  optional    instructionselse:  optional    instructions
for in range(n):    instructionsfor in range(n):    instructions
Built-in Data StructuresBuilt-in Data Structures
Listslinked lists implementing the subscriptoperator:[1,2,3]x.append(4)print x[2]       result: 3Listslinked lists implementing the subscriptoperator:[1,2,3]x.append(4)print x[2]       result: 3
Tupplesconstant kind of arrays(1,2,3)Tupplesconstant kind of arrays(1,2,3)
Dictionariesassociation lists{}x["word"] referencefor in x.keys():    print x[k]Dictionariesassociation lists{}x["word"] referencefor in x.keys():    print x[k]
Functions and ParametersFunctions and Parameters
Function definition:def function_name (par1, par2, ...):    body of the functionFunction definition:def function_name (par1, par2, ...):    body of the function
It supports default values for parameters.It supports default values for parameters.
All parameters are value parameters.All parameters are value parameters.
Any variable storing complex data structurecontains reference to it. Any changes to thecontent of such data structure in the functionwill affect the variable passed in the function call.Any variable storing complex data structurecontains reference to it. Any changes to thecontent of such data structure in the functionwill affect the variable passed in the function call.
Assignments involving complex data structuredon't make copy of it.Assignments involving complex data structuredon't make copy of it.
More Built-in FunctionsMore Built-in Functions
Function typereturns the type of an object.Function typereturns the type of an object.
type(0) – returns <type ‘int’>type(0) – returns <type ‘int’>
Checking if something is an integer:Checking if something is an integer:
if type(x) == type(0): ...if type(x) == type(0): ...
Reading value from the terminal: input()Reading value from the terminal: input()
input()input()
Returning value from function:Returning value from function:
return Truereturn True
Artificial Intelligence – D. Vrajitoru
Example of ConditionalExample of Conditional
def check_type(x):def check_type(x):
    if type(x) == type(0):    if type(x) == type(0):
        print x, "is an integer"        print x, "is an integer"
    elif type(x) == type(1.0):    elif type(x) == type(1.0):
        print x, "is float"        print x, "is float"
    elif type(x) == type(""):    elif type(x) == type(""):
        print x, "is string"        print x, "is string"
    elif type(x) == type([]):    elif type(x) == type([]):
        print x, "is an array"        print x, "is an array"
    ...    ...
Artificial Intelligence – D. Vrajitoru
Example of while/elseExample of while/else
def Euler(a, b):def Euler(a, b):
    if b==0:    if b==0:
        return a        return a
    b    b
    while r:    while r:
        b        b
        r        r
        b        b
    else:    else:
        print "a divisible by b"        print "a divisible by b"
        return b        return b
    return r    return r
Artificial Intelligence – D. Vrajitoru
BooleansBooleans
Truth values: True and False.Truth values: True and False.
False is equivalent with 0, and empty list[], an empty dictionary {}.False is equivalent with 0, and empty list[], an empty dictionary {}.
Anything else is equivalent to True.Anything else is equivalent to True.
Example:Example:
00
if not x:if not x:
print “0 is False”print “0 is False”
Artificial Intelligence – D. Vrajitoru
Default Values for ParametersDefault Values for Parameters
Default values:Default values:
def function (var1 value, var2 value, ...):def function (var1 value, var2 value, ...):
Just like in C++, all the parameters that havedefault values must be grouped at the end.Just like in C++, all the parameters that havedefault values must be grouped at the end.
def GCD1(a=10, b=20): ...def GCD1(a=10, b=20): ...
GCD1() -> 10GCD1() -> 10
GCD1(125) -> 5GCD1(125) -> 5
GCD1(12, 39) -> 3GCD1(12, 39) -> 3
Artificial Intelligence – D. Vrajitoru
Variables and ScopeVariables and Scope
Module: one python file.Module: one python file.
Global scope: exists in the module in which theyare declared.Global scope: exists in the module in which theyare declared.
Local scope: local to the function inside which itis declared.Local scope: local to the function inside which itis declared.
Global variables in module can be accessedfrom somewhere else using the notationmodule.variable.Global variables in module can be accessedfrom somewhere else using the notationmodule.variable.
Example: string.digits contains ‘0123456789’.Example: string.digits contains ‘0123456789’.
Artificial Intelligence – D. Vrajitoru
Example ScopeExample Scope
def test_scope():def test_scope():
    for in range(4):    for in range(4):
        for in range (3):        for in range (3):
            i*10+j            i*10+j
            if x>20:            if x>20:
                print x,                print x,
    print x    print x
test_scope()test_scope()
21 22 30 31 32 3221 22 30 31 32 32
Artificial Intelligence – D. Vrajitoru
Try ExceptTry Except
Try: attempts to execute an instruction.Try: attempts to execute an instruction.
If the operation is successful, it moves on.If the operation is successful, it moves on.
If not, we have the option of doing somethingelse with the instructionIf not, we have the option of doing somethingelse with the instruction
except:except:
Another option:Another option:
except error_type:except error_type:
which does something only for particular typeof exception.which does something only for particular typeof exception.
Artificial Intelligence – D. Vrajitoru
def scope1():def scope1():
    15    15
2020
def scope2():def scope2():
    25    25
def scope3():def scope3():
    try:    try:
        print y        print y
    except:    except:
        print "cannot access global y"        print "cannot access global y"
    print days    print days
    25    25
    print y    print y
days=["monday", "tuesday"]days=["monday", "tuesday"]
Artificial Intelligence – D. Vrajitoru