This is a Doctor,Doctor it hurts when I do this question...but does anyone know why I get a "None" output when running from a module, and I don't get a "None" when I call a function from the Python Shell?
#As an exercise, write a function that takes a string as an #argument and outputs the letters backward, one per line. def spellBackwards(word): loopCount=-1 while -1*loopCount<=len(word): if word[loopCount]==None: return " " else: print (word[loopCount]) loopCount-=1 print (spellBackwards("backwards")) #I do get my backwards spelling, but at the end of that I get a "None". If I #comment out the print statement "None" does not print. What is going on #here? My if/else word[loopCount] apparently does nothing. def spellBackwards1(word): loopCount=1 while loopCount<=len(word): print (word[len(word)-loopCount]) loopCount+=1 print (spellBackwards1("backwards")) #this too gives me a "None" at the end. def spellFrontwards(word): loopCount=0 while loopCount<len(word): print (word[loopCount]) loopCount+=1 print (spellFrontwards("frontwards")) #but if the function is called from the shell I don't get the "None"
All functions return 'None' unless you use the keyword 'return to return something else. The shell suppresses the 'None' return. If you did some_var = spellFrontwards(word) and then print some_var it would show you the 'None'
Instead of using print at the end you could just type spellFrontwards("frontwards") ad your function already does the printing or you could make the function build up a variable with what you want to print and return it, then your last print would work as expected.
Thank You msmithhnova
Here's a recursive way to do it: def reverse( string ): if( len( string ) == 0 ): return char = string[ 0 ] reverse( string[ 1: ] ) print char if( __name__ == "__main__" ): print reverse( "Hello World" )
Thanks rsmith6559, that nice little program will help me think about recursion.
Join our real-time social learning platform and learn together with your friends!