Python: Return value not found in function

a marqué ce sujet comme résolu.

Salut @everyone!

Je galère un peu … Je ne suis pas un pro de python, je débogue un programme chatboot. J’ai mon algorithme, ma fonction build_answer effectue une recherche pour trouver "order_info" dans message, question, history, si après order_info n’a pas été trouvé, alors je voudrais un retour "Not found".

L’aide sera vraiment la bienvenue.

Voici où je suis et ma progression …

def build_answer(shop,order_info,message,questions,history,is_buffalo):

    questions_2 = ["info_not_found","none"]
    history_line = None

    # CASE 1: if the customer has already a question
    for j in range(len(history)):
        if (message["email"] in history[j]):
            if history[j][2] == "no": # Question and then customer_id
                questions_2 = eval(history[j][3].replace("$",","))
                if order_info != {}:
                    response, answer_id = detect_response(shop,questions_2,order_info,message,history)
                    history[j][2] = order_info["customer_id"]

                elif "not_customer" in questions and "status" in questions_2:
                    question_2 = ["status","not_customer"]
                    order_info_2 = {"status":"none","time":400,"order_time":400}
                    response, answer_id = detect_response(shop,questions_2,order_info_2,message,history)
                    
                else:
                    response = "/ALERT I could not find info on this customer"
                    answer_id = "s9"
                    
            elif order_info != {}:
                response, answer_id = detect_response(shop,questions,order_info,message,history)
            else:
                response = "/ALERT I could not find info on this customer"
                answer_id = "s9"
            
            answer_ids = list(eval(history[j][4].replace("$",",")))
            if answer_id not in answer_ids:
                answer_ids.append(answer_id)
            else:
                return "/ALERT This customer often asks me the same question", "/ALERT"
            history[j][4] = str(answer_ids)
            lst = []  #rebuild the file content
            for lst3 in history:
                lst.append(",".join(lst3))
            cont = "\n".join(lst)
            file = open("shops/{}/history.csv".format(shop),"w")
            file.write(cont)
            file.close()
            return response, answer_id
            

    
 
    if order_info != {}:
        response, answer_id = detect_response(shop,questions,order_info,message,history)
        info = order_info["customer_id"]

    else:
        order_info_2 = {"status":"none","time":400,"order_time":400}
        response, answer_id = detect_response(shop,questions_2,order_info_2,message,history)
        info = "no"
    # Build the file content
    answer_ids = []
    answer_ids.append(answer_id)
    if is_buffalo:
        shop = "BUFFALO"
    file = open("shops/{}/history.csv".format(shop),"a")
    content = "\n{},{},{},{},{}".format(message["email"],str(datetime.now())[:-7],info,str(questions).replace(",","$"),str(answer_ids).replace(",","$").replace("\r",""))
    if is_buffalo:
        content += ",{}".format(shop)
    file.write(content)
    file.close()
    return response, answer_id


+0 -0

Voici ma progression :)

J’aimerai avoir votre avis svp ---------------_-

for j in range(len(history)): if (message["email"] in history[j]):

devient:

for history_info in history:
            if message["email"] in history_info:

if order_info != {}:

devient:

if order_info:
file = open(..., "w")
file.write(cont)
file.close()

devient:

with open(..., "w") as f:
        f.write(cont)

lst = [] for lst3 in history: lst.append(",".join(lst3)) cont = "\n".join(lst)

devient:

 lst = [",".join(h) for h in history]
    cont = "\n".join(lst)

cont = "\n".join([",".join(h) for h in history])

devient:

cont = "\n".join(",".join(h) for h in history)

tout ce qui est en dessous de :

Build the file content

devient:

answer_ids = []
        answer_ids.append(answer_id)
        (shop, questions_2, order_info, message, history)
        return response, answer_id

idem pour le code au dessus :

if order_info != {}:
            response, answer_id = detect_response(shop,questions,order_info,message,history)
            info = order_info["customer_id"]
    else:
        order_info_2 = {"status":"none","time":400,"order_time":400}
        response, answer_id = detect_response(shop,questions_2,order_info_2,message,history)
        info = "no"

devient:

response, answer_id, info = prepare_response(shop, questions, order_info, message,history)

De même chose pour plus haut, je pense :

    for j in range(len(history)):
        if (message["email"] in history[j]):
            if history[j][2] == "no": # Question and then customer_id
                questions_2 = eval(history[j][3].replace("$",","))
                if order_info != {}:
                    response, answer_id = detect_response(shop,questions_2,order_info,message,history)
                    history[j][2] = order_info["customer_id"]

                elif "not_customer" in questions and "status" in questions_2:
                    question_2 = ["status","not_customer"]
                    order_info_2 = {"status":"none","time":400,"order_time":400}
                    response, answer_id = detect_response(shop,questions_2,order_info_2,message,history)

                else:
                    response = "/ALERT I could not find info on this customer"
                    answer_id = "s9"

            elif order_info != {}:
                response, answer_id = detect_response(shop,questions,order_info,message,history)
            else:
                response = "/ALERT I could not find info on this customer"
                answer_id = "s9"

            answer_ids = list(eval(history[j][4].replace("$",",")))
            if answer_id not in answer_ids:
                answer_ids.append(answer_id)
            else:
                return "/ALERT This customer often asks me the same question", "/ALERT"
            history[j][4] = str(answer_ids)
            lst = []  #rebuild the file content
            for lst3 in history:
                lst.append(",".join(lst3))
            cont = "\n".join(lst)
            file = open("shops/{}/history.csv".format(shop),"w")
            file.write(cont)
            file.close()
            return response, answer_id

devient :

for j in range(len(history)):
            if (message["email"] in history[j]):
                return handle_email(X, Y, Z)

Ce qui donne la fonction :

def build_answer(shop, order_info, message, questions, history, is_buffalo):
    questions_2 = ["info_not_found", "none"]
    history_line = None

    for j in range(len(history)):
        try:
            if (message["email"] in history[j]):
                return handle_email(questions_2, order_info, message, history)

                response, answer_id, info = prepare_response(shop, questions, order_info, message,history)
        except IOError:
            print("Ordre_info Not found")

        else:
            print("Ordre_info Not found")

    # Build the file content
    answer_ids = [] ;
    answer_ids.append(answer_id);

    log_response(shop, questions_2, order_info, message, history)

    return response, answer_id

Les modifications apportées au code ont l’air pas mal, note cependant que les point-virgules en fin de ligne sont inutiles en Python et donc déconseillés.

Est-ce qu’il reste des choses qui te posent problème sur ton programme ?

Merci beaucoup entwanne :) :D ça m’encourage encore plus !!!!

J’ai une question, le "except IOError" est-il bon si je dois faire une exception au cas ou mon order_info n’est pas trouvé ?

Au cas ou c’est bon, devrai-je mettre "except IOError" ou "except Raise" ?

J’ai une question, le "except IOError" est-il bon si je dois faire une exception au cas ou mon order_info n’est pas trouvé ?

miprotech223

Ça déoend, est-ce que la fonction handle_email est susceptible de lever une exception IOError ?

Au cas ou c’est bon, devrai-je mettre "except IOError" ou "except Raise" ?

miprotech223

Non non ce serait bien except IOError. except Raise voudrait dire que tu as un tyoe d’exceptions appelé Raise et que tu cherches à attraper les exceptions de ce type.

Connectez-vous pour pouvoir poster un message.
Connexion

Pas encore membre ?

Créez un compte en une minute pour profiter pleinement de toutes les fonctionnalités de Zeste de Savoir. Ici, tout est gratuit et sans publicité.
Créer un compte