Function returns old value

Joe Pfeiffer pfeiffer at cs.nmsu.edu
Sat Dec 12 14:51:50 EST 2020


Bischoop <Bischoop at vimart.net> writes:

> On 2020-12-12, Joe Pfeiffer <pfeiffer at cs.nmsu.edu> wrote:
>> Bischoop <Bischoop at vimart.net> writes:
>>
>>> I've function asking question and comparing it, if is not matching 'yes'
>>> it does call itself to ask question again. The problem is that when
>>> function is called second time it returns old value or with additional
>>> else statement it returns none.
>>>
>>> Code: https://bpa.st/KVGA
>>
>> It calls itself again, but what does it return in that case?
>
> I've stated it returns old value that I've input first time, anyway
> output is also inluded in a paste but since you've asked:

Sorry, my question wasn't clear.  What I meant was, "in your return
statement, what are you returning"?

You need to be returning the value from the recursive call.

> def question():
>     ask = input("Are you OK?:").lower()
>         if ask != 'yes':
> 	        question()
> 		    return ask
>
> 		    print (question())
>
> 		    #output:
> 		    Are you OK?:no
> 		    Are you OK?:no
> 		    Are you OK?:yes
> 		    no
>
> 		    ---------------------------------------
> 		    #Another way with 'elif' statment returns none
>
>
> 		    def question():
> 		        ask = input("Are you OK?:").lower()
> 			    if ask != 'yes':
> 			            question()
> 				        elif ask == 'yes':
> 					        return ask
>
> 						print (question())
>
> 						#output:
> 						Are you OK?:no
> 						Are you OK?:yes
> 						None
>
> 						#Tried also nested
> 						functions, same results:
>
> 						def question():
> 						    ask = input("Are you
> 						    OK?:").lower()
>
> 						        def
> 							check_question(n):
> 							        if ask
> 								!=
> 								'yes':
> 								            question()
> 									            else:
> 										                return
> 												ask
>
> 												    m
> 												    =
> 												    check_question(ask)
> 												        print
> 													(m)
> 													question()
>
> 													#output:
> 													Are
> 													you
> 													OK?:no
> 													Are
> 													you
> 													OK?:yes
> 													None
>
> 													Process
> 													finished
> 													with
> 													exit
> 													code
> 													0


More information about the Python-list mailing list