Can you return a print or a message in python?

0

If in a function I can return a print or the message itself that they ask me to give, the exercise says that if the number is inside the list it must tell the user that such a value is in the list and the same in case opposite.

def comprobarEnLista(L):
    print"Ingrese el numero que desea saber si esta o no en la lista"
    n=int(raw_input("Numero a comprobar: "))
    L=[]
    i=0
    while i<len(L):
       for cont in L:
          if n==L[i]:
             print "El valor %d esta en la lista"%n
          else:
             print"El valor %d no esta en la lista"%n
    i+=1       

That's the function that I'm creating, if you could help me, I'd appreciate it a lot

    
asked by Wolf 21.10.2018 в 01:35
source

2 answers

1

Yes, your prints are well made. The rest of the function, rather not.

You can easily check if n is in L with n in L . This returns True if it is in the list, or False otherwise.

def comprobarEnLista(L):
    print"Ingrese el numero que desea saber si esta o no en la lista"
    n=int(raw_input("Numero a comprobar: "))
    if n in L:
        print "El valor %d esta en la lista"%n
    else:
        print "El valor %d no esta en la lista"%n 
    
answered by 21.10.2018 / 03:15
source
0

I do not understand your problem, you are already doing print. The print can not be returned but with execution it is already printed in the console

You can return a message.

In your code I see several problems, the i + = 1 is out of the while, so it never increases and the loop is infinite, it never stops, using two loops is really inecesaeio and inefficient with one already worth:

def comprobarEnLista(L):
    print"Ingrese el numero que desea saber si esta o no en la lista"
    n=int(raw_input("Numero a comprobar: "))
    for z in L:
        if z == n:
           return "El valor %d esta en la lista"%n
        else:
           return "El valor %d no esta en la lista"%n

But the most efficient way is to do it with an if:

def comprobarEnLista(L):
    print"Ingrese el numero que desea saber si esta o no en la lista"
    n=int(raw_input("Numero a comprobar: "))
    if n in L:
       return "El valor %d esta en la lista"%n
    else:
       return "El valor %d no esta en la lista"%n

With if in you check if an item is inside a list

HOW MANY TIMES A VALUE IS REPEATED IN THE LIST

Assuming L is the list and N the number you want to see how many times it is repeated

def cuantas_veces_repite(L, N):
     return L.count(N)
    
answered by 21.10.2018 в 05:43