Error in my code


<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

This code is return a value error : it says that it needs more than one argument to unpack

<What do you expect to happen instead?>


import random
from urllib import urlopen # misspelt urlib and returned a “no module named urlib error”
import sys

word_url = “
words =

phrases = {

     "class %%%(%%%):":
  "Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)" :
  "class %%% has-a __init__ that takes self and *** parameters.",
"class %%%(object):\n\tdef ***(self, @@@)":
  "class %%% has-a function named *** that takes self and @@@ parameters.",
"*** = %%%()":
  "Set *** to an instance of class %%%.",
  "From *** get the *** function, and call it with parameters self, @@@.",
"***.*** = '***'":
  "From *** get the *** attribute and set it to '***'."


do they want to drill phrases first

phrase_first = False
if len (sys.argv) == 2 and sys.argv[1] == “english”:
phrase_first = True

load up the words from the website

for word in urlopen(word_url).readlines() :

def convert(snippet, phrase) :
class_names = [w.capitalize() for w in random.sample(words, snippet.count("%%%"))]
other_names = random.sample(words, snippet.count("***")) # Name error : ‘global name other’ is not defined

# correction : other,names should be other_names
results = []
param_names = []

for i in range(0, snippet.count("@@@")):
    param_count = random.randint(1,3)
    param_names.append(','.join(random.sample(words, param_count)))

for sentence in snippet, phrase:
    result = sentence[:]

# fake class names

for word in class_names:
    result = result.replace("%%%", word, 1) # Type error  : expected a string or other character buffer object
    # correction : word" should be word

    # fake other names

for word in param_names:
    result = result.replace("***", word, 1)

# fake parameter lists

for word in param_names:
    result = result.replace("@@@", word, 1)


return results

Error while creating code : syntax error : ‘return’ outside function

keep going until they hit CTRL-D

while True:
snippets = phrases.keys()

    for snippet in snippets:
        phrase = phrases[snippet] # phrases variable was declared and not phrase
        question, answer = convert(snippet, phrase) # Name error : 'phrase not defined'
        # value error : need more than one value to unpack
        if phrase_first :
            question, answer = answer, question

        print question

        raw_input("> ")
        print "ANSWER:  %S\n\n" % answer

except EOFError:
print “\nBye”

<do not remove the three backticks above>

Are you trying to run this in Python 3? If so, there are some changes to make in the code.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.