Michelle C. Michelle C. - 1 year ago 119
Python Question

Python - function is not returning variable (string)

I'm quite new to Python and this is for programming project in my CS course. The code seems to work perfectly EXCEPT on the last line of code:

return finalWord

does not return anything. I have tried replacing this with:


and it does print everything correctly.

Essentially in the program, I must create a Random class that pseudo-randomly generates numbers and then in the class Nonce, add several different words to the dictionary, and using the dictionary, create new, random words.

class Random:

def __init__(self, seed):
self.seed = seed

def next(self, range):
self.seed = (7 ** 5 * self.seed) % (2 ** 31 - 1)
return self.seed % range

def choose(self, objects):
return objects[self.next(len(objects))]

class Nonce:

def __init__(self, seed):
self.first = []
self.follow = {}
self.random = Random(seed)

def add(self, word):
self.first += [word[0]]
for x in range(0, len(word) - 1):
self.follow.setdefault(word[x], []).append(word[x + 1])
return None

def make(self, size):
nextLetter = self.random.choose(self.first)
finalWord = nextLetter

for x in range(1, size):
if nextLetter in self.follow:
followList = self.follow[nextLetter]
nextLetter = self.random.choose(followList)
finalWord += nextLetter
finalWord += self.random.choose(self.first)

return finalWord

potato = Nonce(101)

Thanks in advance.

Answer Source

If you are calling the function directly, then you must either do something with the returned value (like printing it) or store it in a variable for later use. The code is "not working" because you are never calling the function, at least not in the excerpt that you provided.

Printing the response:


Storing it in a variable:

variable_name = instance_name.make())

The code is where the instance of the class is called instance_name

In your code, you wrote potato.make(5). The function runs, but does not print anything or store it in a variable. To print the response, you would need to do the following:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download