c463 / b551 artificial intelligence dana vrajitoru python

16
C463 / B551 C463 / B551 Artificial Artificial Intelligence Intelligence Dana Vrajitoru Dana Vrajitoru Python Python

Upload: robyn-hensley

Post on 04-Jan-2016

223 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

C463 / B551C463 / B551Artificial IntelligenceArtificial Intelligence

Dana VrajitoruDana Vrajitoru

PythonPython

Page 2: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Python IntroductionPython Introduction

An interpreted, compiled, and interactive, object-An interpreted, compiled, and interactive, object-oriented, dynamic, imperative, and open source oriented, dynamic, imperative, and open source programming language. programming language. Created in early 90's by Guido von Rossum at Stichting Created in early 90's by Guido von Rossum at Stichting Mathematisch Centrum in the Netherlands. Mathematisch Centrum in the Netherlands. The name comes from the Monty Python and not from The name comes from the Monty Python and not from the snake. the snake. There is a big community of Python programmers, with There is a big community of Python programmers, with conferences and magazines:conferences and magazines:http://pycon.org/ http://pycon.org/ Web site: Web site: www.python.org. .

Page 3: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Features of PythonFeatures of Python

Interactive: one can launch a Python console and run Interactive: one can launch a Python console and run instructions directly it. instructions directly it. Portable: available on most existing systems. It only Portable: available on most existing systems. It only requires a C compiler to be ported to any new platform. requires a C 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 C or C++ and The user can write their own code in C or C++ and compile it as Python modules or functions. That makes compile it as Python modules or functions. That makes Python extensible. Python extensible. Usual applications: scripts including CGI scripts, GUIs, Usual applications: scripts including CGI scripts, GUIs, scientific computing. scientific computing. Many existing libraries for all sort of purposes.Many existing libraries for all sort of purposes.

Page 4: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Syntax RulesSyntax Rules

The syntax is designed to be simplified as compared to The syntax is designed to be simplified as compared to other languages like C/C++.other languages like C/C++.Every compound instruction ends with ":"Every compound instruction ends with ":"There are no blocks of code; blocks are implicitly created There are no blocks of code; blocks are implicitly created by indentation.by indentation.Expressions: usual arithmetic operators, named logic Expressions: usual arithmetic operators, named logic operators: and, or, not.operators: and, or, not.Assignments use the = sign but they don't have to end Assignments use the = sign but they don't have to end with ";"with ";"Comments start with # as in shell scripting.Comments start with # as in shell scripting.Variables are declared by assigning them a value and Variables are declared by assigning them a value and they are local to the block where they appear first.they are local to the block where they appear first.

Page 5: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Control StructuresControl Structures

Conditional:Conditional:ifif condition: condition: instructions instructionselifelif condition: #* condition: #* instructions instructionselseelse: # optional: # optional instructions instructions

Loops:Loops:whilewhile condition: condition:    instructions    instructions

elseelse:  # optional:  # optional    instructions    instructions

forfor var var inin S:        S:            instructions    instructions

elseelse:  # optional:  # optional    instructions     instructions

forfor i i inin range(n): range(n):    instructions     instructions

Page 6: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Built-in Data StructuresBuilt-in Data Structures

ListsLists: linked lists implementing the subscript : linked lists implementing the subscript operator:operator:x = [1,2,3]x = [1,2,3]x.append(4)x.append(4)print x[2] # result: 3 print x[2] # result: 3 TupplesTupples: constant kind of arrays: constant kind of arraysx = (1,2,3)x = (1,2,3)DictionariesDictionaries: association lists: association listsx = {}x = {}x["word"] = referencex["word"] = referencefor k in x.keys():for k in x.keys(): print x[k] print x[k]

Page 7: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Functions and ParametersFunctions and Parameters

Function definition:Function definition:defdef function_name (par1, par2, ...): function_name (par1, par2, ...): body of the function body of the functionIt supports default values for parameters.It supports default values for parameters.All parameters are value parameters.All parameters are value parameters.Any variable storing a complex data structure Any variable storing a complex data structure contains a reference to it. Any changes to the contains a reference to it. Any changes to the content of such a data structure in the function content of such a data structure in the function will affect the variable passed in the function will affect the variable passed in the function call.call.Assignments involving a complex data structure Assignments involving a complex data structure don't make a copy of it.don't make a copy of it.

Page 8: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

More Built-in FunctionsMore Built-in Functions

Function Function typetype: returns the type of an object.: returns the type of an object.

type(0)type(0) – returns <type ‘int’> – 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 a value from the terminal: input()Reading a value from the terminal: input()

x = input()x = input()

Returning a value from a function:Returning a value from a function:

return Truereturn True

Artificial Intelligence – D. VrajitoruArtificial Intelligence – D. Vrajitoru

Page 9: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

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 a float"print x, "is a float"

elif type(x) == type(""):elif type(x) == type(""):

print x, "is a string"print x, "is a string"

elif type(x) == type([]):elif type(x) == type([]):

print x, "is an array"print x, "is an array"

......

Artificial Intelligence – D. VrajitoruArtificial Intelligence – D. Vrajitoru

Page 10: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Example of while/elseExample of while/else

def Euler(a, b):def Euler(a, b):

if b==0:if b==0:

return areturn a

r = a % br = a % b

while r:while r:

a = ba = b

b = rb = r

r = a % br = a % b

else:else:

print "a divisible by b"print "a divisible by b"

return breturn b

return rreturn rArtificial Intelligence – D. VrajitoruArtificial Intelligence – D. Vrajitoru

Page 11: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

BooleansBooleans

Truth values: True and False.Truth values: True and False.

False is equivalent with 0, and empty list False is equivalent with 0, and empty list [], an empty dictionary {}.[], an empty dictionary {}.

Anything else is equivalent to True.Anything else is equivalent to True.

Example:Example:x = 0x = 0

if not x:if not x:

print “0 is False”print “0 is False”

Artificial Intelligence – D. VrajitoruArtificial Intelligence – D. Vrajitoru

Page 12: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

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 have Just like in C++, all the parameters that have default values must be grouped at the end.default 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. VrajitoruArtificial Intelligence – D. Vrajitoru

Page 13: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Variables and ScopeVariables and Scope

Module: one python file.Module: one python file.

Global scope: exists in the module in which they Global scope: exists in the module in which they are declared.are declared.

Local scope: local to the function inside which it Local scope: local to the function inside which it is declared.is declared.

Global variables in a module can be accessed Global variables in a module can be accessed from somewhere else using the notation from somewhere else using the notation module.variable.module.variable.

Example: string.digits contains ‘0123456789’.Example: string.digits contains ‘0123456789’.

Artificial Intelligence – D. VrajitoruArtificial Intelligence – D. Vrajitoru

Page 14: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

Example ScopeExample Scope

def test_scope():def test_scope():

for i in range(4):for i in range(4):

for j in range (3):for j in range (3):

x = i*10+jx = i*10+j

if x>20:if x>20:

print x,print x,

print xprint x

test_scope()test_scope()

21 22 30 31 32 3221 22 30 31 32 32Artificial Intelligence – D. VrajitoruArtificial Intelligence – D. Vrajitoru

Page 15: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

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 something If not, we have the option of doing something else with the instructionelse with the instruction

except:except:

Another option: Another option:

except error_type:except error_type:

which does something only for a particular type which does something only for a particular type of exception.of exception.

Artificial Intelligence – D. VrajitoruArtificial Intelligence – D. Vrajitoru

Page 16: C463 / B551 Artificial Intelligence Dana Vrajitoru Python

def scope1():def scope1():

y = 15y = 15

y = 20y = 20

def scope2():def scope2():

y = 25y = 25

def scope3():def scope3():

try:try:

print yprint y

except:except:

print "cannot access global y"print "cannot access global y"

print daysprint days

y = 25y = 25

print yprint y

days=["monday", "tuesday"]days=["monday", "tuesday"]

Artificial Intelligence – D. VrajitoruArtificial Intelligence – D. Vrajitoru