how do the elements of a list go from one function to another?

0

I would like to know how to pass the list of the function "repeat_question" to the function "main". I try with "return name" but it does not happen. In what failure?

def main():

    print('escribe algunos nombres y luego presiona enter:')        

    a = []

    repite_pregunta(a)

    print('los nombres que escribiste son:')

    print (a)


def repite_pregunta (nombre):

  nombre = []
  re_ingresar = True

  while re_ingresar:
    nombre.append(input())

    if name[-1] == '' :

      re_ingresar = False

  return nombre 


main()

Example of output I would like:

escribe algunos nombres y luego presiona enter:
juan
pepe
rafael

los nombres que escribiste son:
['juan','pepe','rafael']

the ouput with the current code:

escribe algunos nombres y luego presiona enter:
juan
pepe
rafael

los nombres que escribiste son:
[]
    
asked by juan 07.11.2018 в 05:07
source

1 answer

0

In the repite_pregunta() function you empty the nombre list when you make nombre=[] . On the other hand the return nombre that you do at the end would be superfluous since the function is changing anyway the list received through the parameter, so you do not need to return it (also from main() you do not assign the value returned by the function ).

So it could look like this:

def repite_pregunta (nombre):
  re_ingresar = True

  while re_ingresar:
    nombre.append(input())
    if nombre[-1] == '' :
      re_ingresar = False

And call it like that (like you had):

a = []
repite_pregunta(a)

However, it is not advised that the functions modify the parameters. In fact, in general it is not even possible to do it unless it is a list (as in this case). For consistency and to make it easier to reason about the program, it is advised that the functions do not change the value of the parameters, but return the result through a return .

With this approach the function would not need parameters. It would be called like this:

a = input_nombres()

and it would be implemented like this:

def input_nombres():
  re_ingresar = True
  nombres = []

  while re_ingresar:
    nombres.append(input())
    if nombres[-1] == '' :
      re_ingresar = False
  return nombres

(I have used to change the name of the list to nombres , since it will contain more than one, and that of the function to input_nombres() , since that is what it does.) Choosing suitable variable names is also very important to help understand the code).

    
answered by 07.11.2018 в 08:01