Computer Sciences Department logo

CS 368-4 (2011 Fall) — Day 5 Scripts

The scripts from class today are copied below. Mostly, the code comes from the slides, but with a bit of extra output formatting.

Defining and Using Functions (Slides 12–13)

def greet_world():
    print 'Hello, world!'
    print '2 + 2 =', str(2 + 2)
    print 'And now, goodbye.'

print 'PART 1'
greet_world()
print '-' * 20
greet_world()
print

print 'PART 2'
def greet_person(name):
    print 'Hello, %s!' % (str(name))
greet_person('Tim')
greet_person(raw_input('Enter name: '))

Variable Scoping With Functions (Slide 16)

print 'VERSION 1'
y = 0
def linear_1(x):
    # ...
    y = 2 * x + 1
    print 'Inside:', y
linear_1(42)
print 'Outside:', y
print

print 'VERSION 2'
y = 0
def linear_2(x):
    global y
    y = 2 * x + 1
    print 'Inside:', y
linear_2(42)
print 'Outside:', y