This may be an easy question to answer, but I can't get this simple program to work and it's driving me crazy. I have this piece of code:
def Dat_Function():
my_var = raw_input("Type \"a\" or \"b\": ")
if my_var != "a" and my_var != "b":
print "You didn't type \"a\" or \"b\". Try again."
print " "
Dat_Function()
else:
print my_var, "-from Dat_Function"
return my_var
def main():
print Dat_Function(), "-From main()"
main()
Now, if I input just "a" or "b",everything is fine. The output is:
Type "a" or "b": a
a -from Dat_Function
a -From main()
But, if I type something else and then "a" or "b", I get this:
Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
a -from Dat_Function
None -From main()
I don't know why Dat_Function()
is returning None
, since it should only return my_var
. The print statement shows that my_var
is the correct value, but the function doesn't return that value for some reason.
It is returning
None
because when you recursively call it:..you don't return the value.
So while the recursion does happen, the return value gets discarded, and then you fall off the end of the function. Falling off the end of the function means that python implicitly returns
None
, just like this:So, instead of just calling
Dat Function()
in yourif
statement, you need toreturn
it.To return a value other than None, you need to use a return statement.
In your case, the if block only executes a return when executing one branch. Either move the return outside of the if/else block, or have returns in both options.
I think that you should use while loops.
Consider that you type something different than "a" and "b", of course, it will call
Dat_Function
but then it is skipping the next part. Which is:And will go directly into:
So, if you use while loop as:
This way I think that you can handle it.