Reputation: 21
I am trying to create a program that will take two sets of random integers, and print a statement based on the results of those two sets of integers. However, when I call the method, I either receive "None" or an error stating "maximum recursion depth exceeded". I can't seem to figure out how to structure my return statements within these methods so that this works properly.
def genre(a,b):
genreType = random.randint(a,b)
if genreType == '1':
genreType = "Fantasy"
return genre()
elif genreType == '2':
genreType = "Sci-Fi"
return genre()
def medium():
mediumType = random.randint(1,2)
if mediumType == '1':
genre = genre(1,2)
print("Play a " + genre + "game")
return medium()
elif mediumType == '2':
genre = genre(1,2)
print("Watch a " + genre + "anime")
return medium()
Upvotes: 2
Views: 78
Reputation: 7353
First, if a function has a branch without a return
, it will return None
, e.g.:
def something():
if False:
return "Thing"
# There is no return in "else"
print(something()) # None
Second, comparing numbers to strings never succeeds:
print(1 == 1) # True
print(1 == '1') # False
So the example you've provided can only always return None
Third, you are not returning anything meaningful from your functions:
def genre(a,b):
genreType = random.randint(a,b)
if genreType == '1':
genreType = "Fantasy"
return genre() # call this function again, but with no parameters, why?!
If the condition had a chance of being true, you would be getting
TypeError: genre() missing 2 required positional arguments: 'a' and 'b'
I can only guess that you meant to do this:
if genreType == 1:
genreType = "Fantasy"
return genreType
Or, shorter and arguably more readable:
def genre(a,b):
genreType = random.randint(a,b)
if genreType == 1:
return "Fantasy"
elif genreType == 2:
return "Sci-Fi"
# And you can add your own error to know what exactly went wrong
else:
raise Exception("Genre bounds must be between 1 and 2")
Upvotes: 2