Michelle C. Michelle C. - 1 month ago 5
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:

print(finalWord)


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
else:
finalWord += self.random.choose(self.first)

return finalWord

potato = Nonce(101)
potato.add('python')
potato.add('java')
potato.add('html')
potato.make(5)


Thanks in advance.

Answer

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:

print(instance_name.make())

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:

print(potato.make(5))
Comments