Learn python the hard way course Ex 25 NameError:

428 views Asked by At

I get this error when I try and run this script

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'print_first_word' is not defined

I'm not sure what it means as when I run import E25; dir(E25) it lists print_first_word in the dir(E25) result.

I'm running python 2.7.9 on Windows

def break_words(stuff):
     """ this function will break up words for us."""
     words = stuff.split('  ')
     return words

def sort_words(words):
     """ sorts the words."""
     return sorted(words)

def print_first_word(words):
     """ prints the first words after popping it off."""
     word = words.pop(0)
     print word

def print_last_word(words):
     """ prints the last words after popping it off."""
     word = words.pop(-1)
     print word

def sort_sentence(sentence):
     """ takes in a full sentence and returns the sorted words."""
     words = break_words(sentence)
     return sort_words(words)

def print_first_and_last(sentence):
     """prints the first and last words of  a sentence."""
     words = break_words(sentence)
     print_first_word(words)
     print_last_word(words)

def print_first_and_last_sorted(sentence):
     """sorts the words then prints the first and last one."""
     words = sort_sentence(sentence)
     print_first_word(words)
     print_last_word(words)





     import E25
2 sentence = ”All good things come to those who wait.”
3 words = ex25.break_words(sentence)
4 words
5 sorted_words = ex25.sort_words(words)
6 sorted_words
7 ex25.print_first_word(words)
8 ex25.print_last_word(words)
9 words
10 ex25.print_first_word(sorted_words)
11 ex25.print_last_word(sorted_words)
12 sorted_words
13 sorted_words = ex25.sort_sentence(sentence)
14 sorted_words
15 ex25.print_first_and_last(sentence)
16 ex25.print_first_and_last_sorted(sentence)
2

There are 2 answers

11
Padraic Cunningham On

You imported E25 but you are using ex25.prin.... which is not the same as E25.print.... According to your error though you are not using E25 or ex25 to call the function.

You might also want to change words = stuff.split(" ") to words = stuff.split().

0
Kirito On
  1. I think you might have two spaces between the single brackets; try to limit to one and try, I tried to remove space by just putting '' instead of ' ', and the code did not work.
  2. Delete the pyc file from the folder and restart your powershell
  3. Try to run the process again, but in case your folder is somewhere on your desktop like me instead of just from the C drive, try to go back to your location first by the set-location command; once you are in the folder, type "python" to go back to the >>> and start the practice.

I hope this helps

def break_words(stuff):
     """ this function will break up words for us."""
     words = stuff.split('^')
     return words