I'm new to coding, and I'm trying to write a program to create a little online store through the terminal. Here is the code:
global balance
def homescreen():
print("What would you like to do?")
print('1. Sign up')
print("2. Login")
option = int(input())
if option == 1:
sign_up()
elif option == 2:
login()
else:
print("Invalid option")
homescreen()
def sign_up():
global username
global password
username = input("Enter a username: ")
password = input("Enter a password: ")
homescreen()
def login():
user = input("Enter your username: ")
passw = input('Enter your password: ')
if user == username and passw == password:
print("Welcome")
homepage()
else:
print('Incorrect password or username; please try again')
login()
def homepage():
print("Welcome, what would you like to do?")
print('1. Shop')
print("2. Check Balance")
print("3. Add money")
option = int(input())
if option == 1:
shop()
elif option == 2:
check_balance_page()
else:
print("Invalid option")
homepage()
def check_balance_page():
balance = 0
print("Your balance is: ", balance)
print('What would you like to do?')
print('1. Go to homepage')
print('2. Add money to balance')
opt = int(input())
if opt == 1:
homepage()
elif opt == 2:
add_money()
else:
print("Invalid option")
check_balance_page()
def add_money():
print("How much money would you like to add?")
amount = int(input())
balance += amount
homepage()
def shop():
print('x')
homescreen()
Whenever I run this, I create sign up, login, and enter the check balance screen and then the add money screen. But when I enter an amount to add to the balance, i get this error message (XXXXXX represents my user path):
Traceback (most recent call last):
File "C:\Users\XXXXXX\Documents\pycharm projects\main.py", line 78, in <module>
File "C:\Users\XXXXXXXX\Documents\pycharm projects\main.py", line 8, in homescreen
option = int(input())
File "C:\Users\XXXXXXXX\Documents\pycharm projects\main.py", line 21, in sign_up
username = input("Enter a username: ")
File "C:\Users\XXXXXXXXXXXX\Documents\pycharm projects\main.py", line 10, in homescreen
sign_up()
File "C:\Users\XXXXXXXXXXXXX\Documents\pycharm projects\main.py", line 29, in login
if user == username and passw == password:
File "C:\Users\XXXXXXXXXXXX\Documents\pycharm projects\main.py", line 45, in homepage
elif option == 2:
File "C:\Users\XXXXXXXXXXXX\Documents\pycharm projects\main.py", line 62, in check_balance_page
add_money()
File "C:\Users\XXXXXXXXXXXXX\Documents\pycharm projects\main.py", line 71, in add_money
balance += amount
UnboundLocalError: local variable 'balance' referenced before assignment
Is there a kind soul who would tell me what's wrong with this?