Monday, October 5, 2009

Chapter 3 Assignments

3.8.1

def new_line():

print


def three_lines():

new_line()

new_line()

new_line()


def nine_lines():

three_lines()

three_lines()

three_lines()


def clear_screen():

nine_lines()

nine_lines()

three_lines()

three_lines()

new_line()

clear_screen()

3.8.2

clear_screen()


def new_line():

print


def three_lines():

new_line()

new_line()

new_line()


def nine_lines():

three_lines()

three_lines()

three_lines()


def clear_screen():

nine_lines()

nine_lines()

three_lines()

three_lines()

new_line()


Traceback (most recent call last):

File "tryme3_2.py", line 3, in <module>

clear_screen()

NameError: name 'clear_screen' is not defined

  • Function calls must come after a function definition. If not, the function will be undefined.

3.8.3
def three_lines():

new_line()

new_line()

new_line()


def new_line():

print


def nine_lines():

three_lines()

three_lines()

three_lines()

def clear_screen():

nine_lines()

nine_lines()

three_lines()

three_lines()

new_line()


clear_screen()

  • This still works because the function definitions all come before the call that incorporates all the definitions regardless of order.

def three_lines():
new_line()
new_line()
new_line()

three_lines()

def new_line():
print

Traceback (most recent call last):
File "/home/louis/bin/exercise3.8.3", line 8, in <module>
three_lines()
File "/home/louis/bin/exercise3.8.3", line 4, in three_lines
new_line()
NameError: global name 'new_line' is not defined

  • This does not work because the function three_lines() requires the function new_line() which is not defined until after the function call of three_lines

3.8.4
def cat_n_times(s, n):
print s*n

>>> from import_test import*
>>> cat_n_times("Cats have nine lives. ", 9)
Cats have nine lives. Cats have nine lives. Cats have nine lives. Cats have nine lives. Cats have nine lives. Cats have nine lives. Cats have nine lives. Cats have nine lives. Cats have nine lives.

1 comment:

  1. Since python source code relies on white space for block structure, it will be important to preserve the formatting in your code examples. Remind me to show you how to do this.

    ReplyDelete