I'm working on this project and I keep getting this problem when the code tries to return the "guess" variable, instead of returning the value of "guess" it goes to line 9 which converts the value into a string for some reason, and then returns that. when I go to use the returned value in something, Python says that the value is "NoneType".
def ask_question(max_length, rowOrCol, guessNumber):
guess = raw_input("What is the "+rowOrCol+" number of your "+guessNumber+" guess? ")
try:
guess = int(guess)
if guess <= max_length:
return guess
else:
print "That number was too big, it must be no larger then " +str(max_length)
ask_question(max_length, rowOrCol, guessNumber)
except(TypeError):
print "Only numbers are accepted, please try again!"
ask_question(max_length, rowOrCol, guessNumber)
I call the function with this line:
first_guess_row = ask_question(4, "row", "first")
Is there anything that I'm missing?
of course all your branches need to return....
...
else:
print "That number was too big, it must be no larger then " +str(max_length)
return ask_question(max_length, rowOrCol, guessNumber)
except(TypeError):
print "Only numbers are accepted, please try again!"
return ask_question(max_length, rowOrCol, guessNumber)
before you were recalling the function ... but you were throwing away its return value
for lines 9 and 12, you are doing a recursive call.
A recursive call is a brand new call to the function within the function. The new call to ask_question, assuming line 6 is executed, is returning a value. but it is returned within the original ask_question call.
Therefore you need to change
ask_question(max_length, rowOrCol, guessNumber)
on line 9 and 12 to
return ask_question(max_length, rowOrCol, guessNumber)
to retrieve that value.
Another Note : recursive calls use extra memory for each recursion, which can cause slowdowns or even crash python (if you recurse a lot, depending on the size of the function). I would recommend putting your code into a loop like this:
continue_asking = True
while continue_asking:
guess = raw_input("What is the "+rowOrCol+" number of your "+guessNumber+" guess? ")
try:
# typecheck the guess value
guess = int(guess)
except (TypeError):
print "Only numbers are accepted, please try again!"
continue
if guess <= max_length:
return guess
else:
print "That number was too big, it must be no larger then " +str(max_length)
Here's another method without using recursive function calls.
def ask_question(max_length, rowOrCol, guessNumber):
while True:
try:
guess = int(raw_input("What is the "+rowOrCol+" number of your "+guessNumber+" guess? "))
if guess <= max_length:
return guess
else:
print "That number was too big, it must be no larger then " +str(max_length)
except(ValueError):
print "Only numbers are accepted, please try again!"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.