First you have to understand that return
is a reserved python word, which serves to return a value and terminate the function. So the return
is executed, the function to. Therefore, its function pergunta()
will ask for an integer number and save it in the variable t
, if that number is less than 3
, the function will print tente outro
on the screen, will return the value of t
and end the execution. However, this returned value is not being stored in any corner, so it is lost. If you want the function to run again, instead of terminating, remove the return
, replacing it with a recursive call. So:
def pergunta():
t = int(input('digite um numero: '))
dois = t<3
if dois:
print ('tente outro')
pergunta()
else:
print ('esse numero ai, parabéns')
pergunta()
The difference here is that when the if dois
is executed, the printa function tente outro
on the screen and calls itself. That is, the function is executed by itself, this is what is called recursiveness. Now let’s better understand the workings of return
. As already said, it terminates the function and returns a value, consider the example:
def pergunta():
t = int(input('digite um numero: '))
dois = t<3
if dois:
print ('valor menor que 3')
return t
else:
print ('valor maior ou igual a 3')
return t
pergunta()
A simple program that collects a value, tells whether it is less than three and returns the said value. The question here is, if it returns a value, where is it stored? Well, this should be specified in the code. Imagine a program consisting of a single line of code:
4
This program does absolutely nothing. If we want to store that value somewhere, ideally:
algumLugar = 4
The same goes for the functions, if we want to store the function return pergunta()
somewhere, we should, rather than:
pergunta()
Use:
retorno = pergunta()
So the value of t
, which is what the function returns, will be stored in the variable retorno
, and to see this value, just add a print(retorno)