C463 / B551 Artificial Intelligence

Introduction to Python

Python Overview

Features of Python

Syntax Rules

Control Structures

Built-in Data Structures

Functions and Parameters

More Built-in Functions

Example of Conditional

def check_type(x):
    if type(x) == type(0):
        print x, "is an integer"
    elif type(x) == type(1.0):
        print x, "is a float"
    elif type(x) == type(""):
        print x, "is a string"
    elif type(x) == type([]):
        print x, "is an array"
    elif type(x) == type({}):
        print x, "is a dictionary"
    else:
        print x, "is probably an object of a class"
    

Example of while/else

def Euler(a, b):
    if b==0:
        return a
    r = a % b
    while r:
        a = b
        b = r
        r = a % b
    else:
        print "a divisible by b"
        return b
    return r

Booleans

Default Values for Parameters

Variables and Scope

Example Scope

def test_scope():
    for i in range(4):
        for j in range (3):
            x = i*10+j
            if x>20:
                print x,
    print x
test_scope()
21 22 30 31 32 32

Try - Except

def scope1():
    y = 15
y = 20
def scope2():
    y = 25
def scope3():
    try:
        print y
    except:
        print "cannot access global y"
    print days
    y = 25
    print y
days=["monday", "tuesday"]

More examples in the file examples1.py.