0

I tried making 2 functions that use sqlite3 in python but when I run the code the functions would run even when not called.

Whenever I run the program set_prod_ID() would run even though I only called for get_product_ID()

here is my code:

import sqlite3

conn = sqlite3.connect('productList.db')

c = conn.cursor()


def set_prod_ID(prodName=input("Please put product name to be changed: "), idNo=input("Please input new product ID: ")):
    conn = sqlite3.connect('productList.db')
    c = conn.cursor()
    #   prodName
    #   idNo
    c.execute("""UPDATE products  SET ID = (?)
                WHERE NAME = (?)

   """, (idNo, prodName))
    conn.commit()
    conn.close()


def get_product_ID(prodName=input("Please input the Name of the product: ")):
    conn = sqlite3.connect('productList.db')
    c = conn.cursor()
    c.execute("SELECT * from products WHERE NAME = (?)", (prodName,))
    items = c.fetchall()

    for item in items:
        print(item[0])


    conn.commit()
    conn.close()

get_product_ID()

1 Answer 1

1

Your problem has nothing to do with sqlite, it occurs on a more basic level of understanding the python language.

When executing a python file, only the function definitions are interpreted, but not the contents yet. Those contents are interpreted when you call the function in a later stage.

Check the below example:

def func_1(inp=input("First function initialized!")):
    print(f"First function executed. At initialization, you entered: {inp}")

def func_2(inp=input("Second function initialized!")):
    print(f"Second function executed. at initialization, you entered: {inp}")

func_1()

It generated the following:

>>> First function initialized!hi
>>> Second function initialized!boo
>>> First function executed. At initialization, you entered: hi

hi and boo are my actual inputs. Only the print-statement in the function that is actually called gets executed.

Sign up to request clarification or add additional context in comments.

5 Comments

How do I not make the prompts not appear unless called? btw thanks for answering sir
You simply add the input prompt in the body of the function, not the definition, where the print-statements are in my example.
Is it possible to only get the "Second function inititialized!" prompt when func_2() is called?
The example is reaching it's limits. In general: If you put an input("...") statement within the function body, it only shows when you call the function. If you put it in the definition line, it show during initialization. Move the lines in my example around and edit them to see what happens.
Can you please accept the answer? It gets us both some reputation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.