-1

I have written 2 pieces of code.

  1. login and authentication
 def register():
    db = open("database.txt","r")
    account_number= input("Enter your Account Number: ")
    pin = input("Create a 4-digit pin: ")
    pin1 = input("Confirm Pin: ")
    d = []
    f = []
    for i in db:
        a,b = i.split(", ")
        b = b.strip()
        d.append(a)
        f.append(b)
    data = dict(zip(d,f))
    print(data)

    if pin != pin1:
        print("Pins don't match, try again!")
        register()
    else:
        if len(pin) != 4:
            print("Pin is not 4-digit. Pin must be 4-digit")
            register()
        elif account_number in d:
            print("account number already exists")
            register()
        else:
            db = open("database.txt","a")
            db.write(account_number+", "+pin+", 0" "\n")
            print("Success!")
    db.close()


def access():
    db = open("database.txt", "r")
    account_number = input("Enter your account number: ")
    pin = input("Enter your pin: ")

    if not len(account_number or pin)<1:
        d = []
        f = []
        for i in db:
            a, b = i.split(", ")
            b = b.strip()
            d.append(a)
            f.append(b)
        data = dict(zip(d, f))

        try:
            if data[account_number]:
                try:
                    if pin== data[account_number]:
                        print("Login Success")
                    else:
                        print("Pin or Account Number Incorrect")
                except:
                    print("Pin or Account Number Incorrect")
            else:
                print("Account Number doesn't exist")
        except:
            print("Login error")
    else:
        print("Please Enter your login credentials")
    db.close()
def home(option = None):
    option = input("Login | Signup: ")
    if option == "Login":
        access()
    elif option == "Signup":
        register()
    else:
        print("Please choose an option")
home()


  1. money transactions
choice = 0
while choice != 4:
      print("\n\n**** Menu *****")
      print("1 -- balance")
      print("2 == deposit")
      print("3 == withdraw")
      print("4 == cancel\n")

      choice=int(input("\nEnter your option:\n"))
      if choice==1:
             print("Balance = ", +balance)
      elif choice==2:
           dep=int(input("Enter your deposit: "))
           balance+=dep
           print("\n deposited amount: " , +dep)
           print("balance = ", +balance)
      elif choice==3:
           wit=int(input("Enter the amount to withdraw: "))
           balance -= wit
           print("\n withdrawn amount: " , +wit)
           print("balance =", +balance)
      elif choice ==4:
           print('Session ended,goodbye.')
      else:
           print("Invalid Entry")

The first code stores an account number and pin in the database. The balance should be 0 automatically for a new account. What can I do to automatically set the balance to 0 and store it in the database?

What should I do to only allow numerical values?

How can I connect the second code to the database in the first code?

  • 2
    Welcome to [Stack Overflow.](https://stackoverflow.com/ "Stack Overflow") Please be aware this is not a code-writing or tutoring service. We can help solve a single specific, technical problem, not open-ended requests for code or advice. Please edit your question to show what you have tried so far, and what specific problem you need help with. See the [How To Ask a Good Question](https://stackoverflow.com/help/how-to-ask "How To Ask a Good Question") page for details on how to best help us help you. – itprorh66 Feb 05 '22 at 15:12
  • @itprorh66 that wasn't my intention. i just want to know how to connect the second code to the database in the first code – coding account Feb 05 '22 at 15:15
  • Move the db connection outside of the register function and make it accessible to both functions – itprorh66 Feb 05 '22 at 15:21
  • This is clearly three questions. For "automatically set the balance to 0", that's already the value written by `register`, so I don't see an issue. For "What should I do to only allow numerical values?", please see https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers. For the other question, I'm not clear on what you mean by "connect", but did you perhaps try `import`ing the other file and calling its functions? We can't *design* the program for you, though. Anyway, please read [ask] and https://stackoverflow.com/help/minimal-reproducible-example. – Karl Knechtel Feb 05 '22 at 15:29

1 Answers1

0

Your first question is how you can automatically create an account with a balance of 0. Unless I am mistaken and the 0 is something else you are already doing that with this line: db.write(account_number+", "+pin+", 0" "\n").

I don't know what issue you are encountering but I could see a potential problem because you are opening the database in write('w') mode and then open it in append('a') mode. You can't do both at the same time, you have to close it beforehand.

Your second question is a bit more complicated to answer, you'll either have to create classes or structure your program differently.

To make it easy for ourselves we'll just load the database into memory. This is most of the logic already, implement your menu in the main loop:

DB_FILE = "database.txt"

db = {}
with open(DB_FILE, 'r') as f:
    db_lines = f.read().splitlines()

for line in db_lines:
    acc_num, pin, balance = line.split()
    db[acc_num] = {'pin': pin, 'balance': int(balance)}


def update_db():
    with open(DB_FILE, 'w') as f:
        for acc_num, data in db.items():
            f.write(acc_num + " " + data['pin'] + " " + str(data['balance']))


def register(acc_num, pin):
    db[acc_num] = {'pin' : pin, 'balance': 0}
    update_db()

def access(acc_num, pin):
    if db[acc_num]['pin'] == pin:
        return True
    return False

def withdraw(acc_num, amount):
    db[acc_num]['balance'] -= amount
    update_db()


def deposit(acc_num, amount):
    db[acc_num]['balance'] += amount
    update_db()

login = False
while True:
    if not login:
        choice = input('register or access')
        if choice == 'access':
            acc_num = input('accnum')
            pin = input('pin')
            if access(acc_num, pin):
                login = True
        elif choice == 'register':
            # get acc num + pin
            register(acc_num, pin)
            login = True   
    else:
        # withdraw and deposit
Carl
  • 183
  • 1
  • 7
  • the line ``` db.write(account_number+", "+pin+", 0" "\n") ``` only adds a 0 in the txt file, but nowhere in my code does that 0 correspond to the balance i cant quite grasp the concept of pseudocode. will i paste that after both pieces of code or in will my code go in between the pseudo code. Sorry I am a coding novice. I hope it isnt too much trouble explaining this stuff to me. – coding account Feb 05 '22 at 15:30
  • I pretty much did your program, you'll only have to implement the menu stuff. I separated your database values by spaces, so you'll have to change that. – Carl Feb 05 '22 at 15:50
  • I somewhat understand what you have done. I will try to work on this further. Thanks a ton! How can i message you if i have any more doubts? – coding account Feb 05 '22 at 15:55