2017-05-21 3 views
0

코드 :한 함수의 변수를 다른 함수의 파이썬으로 가져 오는 방법은 무엇입니까?

def create_Table(): 
    c.execute('CREATE TABLE IF NOT EXISTS customer(name TEXT NOT NULL, accountNo INTEGER NOT NULL, balance INTEGER NOT NULL)') 
    conn.commit() 

def data_insert(): 
    name = str(input("Enter your name: ")) 
    accountNo = random.randrange(2016000,2025000) 
    balance = int(input("Enter your initial deposit: $")) 
    if balance>0: 
     print("You have successfully opened an account, your account number is: ",accountNo) 
    else: 
     print("Incorrect initial deposit, Please deposit $1 or more") 
    c.execute("INSERT INTO customer VALUES(?, ?, ?)",(name, accountNo, balance)) 


def authentication(): 
    user_Id_Input = int(input("Enter your account number: ")) 
    c.execute("SELECT * FROM customer WHERE accountNo = ?",(user_Id_Input,)) 
    return user_Id_Input 
    conn.commit() 

def user_balance(): 
    authentication() 
    if c.fetchall() is not None: 
     c.execute("SELECT balance FROM customer WHERE accountNo = ? "(user_Id_Input,)) 
     data = c.fetchone() 
     print("Your balance is: $",data) 
    else: 
     print("You have entered an incorrect account number.") 
    conn.commit() 

나는 def user_balance():def authentication():에서 변수 user_Id_Input을 싶어. 비록 내가 을 def user_balance():에 코딩 했음에도 나는 여전히 변수를 balance() 함수로 가져올 수 없다.

+0

당신은'authentication()'에서'user_Id_Input'을 리턴하지만'user_balance()'에서 반환 된 값을 포착하지 않습니다. user_balance()에서'user_Id_Input = authentication()'을 사용하십시오. 또한 당신은'return()'문 앞에서'conn.commit()'을'authentication()'으로 옮겨야합니다. – kuro

답변

0

당신은 authentication()에서 user_Id_Input를 반환하지만 user_balance()에 반환 값을 캡처하지 않습니다. 그래서 반환 된 값이 손실됩니다. 사용 -

user_Id_Input = authentication() 

user_balance() 그렇게하면 반환 된 값을 캡처 할 수 있습니다.

반환을 피하고 다른 기능에서 user_Id_Input에 액세스하려는 경우 user_Id_Input을 전역으로 설정할 수 있습니다. 그런 다음 적절한 방법으로 액세스 할 수 있습니다.

이제 코드를 개선하고 싶은 부분을 지적하고자합니다. 먼저 conn.commit()return 진술 전에 authentication()으로 이동해야합니다. data_insert()에서 기능의 끝에서 commit을 수행하려고합니다. 한 가지 더, 테이블 customer에 대한 기본 키를 추가하는 것이 좋습니다. data_insert()에서 사용자가 음수를 제공했거나 입금액을 0으로 지정하면 사용자에게 잘못된 잔액에 대해 경고하지만 동일한 값으로 코드를 삽입하지 않습니다.

+0

그랬지만 오류가 발생했습니다 :'c.execute ("SELECT balance FROM customer WHERE accountNo =?"(user_Id_Input ,)) TypeError : 'str'개체를 호출 할 수 없습니다. ' –

+0

쉼표가 누락 되었기 때문에. 그것은'c.execute ("SELECT balance from customer WHERE accountNo =?", (user_Id_Input,)) ' – kuro

+0

@enochronchi는 문제를 해결합니까? – kuro

관련 문제