I'm writing an ATM program for a class project, and we're not allowed to use global variables. I used only local variables in my program, but it doesn't work.
def welcome():
print("Welcome to the ATM program!\nThis program allows you to deposit, withdraw, or view your balance!")
def menu():
print("1...Deposit\n2...Withdraw\n3...View Balance")
userChoice = int(input("Please enter your choice now: "))
if userChoice == 1:
def deposit(balance):
deposit = float(input("Please enter the amount you would like to deposit: "))
balance = balance + deposit
elif userChoice == 2:
def withdraw(balance):
withdraw = float(input("Please enter the amount you would like to withdraw: "))
balance = balance + withdraw
else:
def balance(balance):
print("Your balance is", balance)
deposit()
withdraw()
balance()
welcome()
menu()
When I run it, it just ends after I input a choice from the menu without any error messages.
There's no reason to define functions here - just execute that code in the if statements, instead:
def menu(balance):
print("1...Deposit\n2...Withdraw\n3...View Balance")
userChoice = int(input("Please enter your choice now: "))
if userChoice == 1:
deposit = float(input("Please enter the amount you would like to deposit: "))
balance = balance + deposit
elif userChoice == 2:
withdraw = float(input("Please enter the amount you would like to withdraw: "))
balance = balance + withdraw
else:
print("Your balance is", balance)
return balance
...
balance = 0
balance = menu(balance)
The reason nothing is happening is because, with the way your code is now, you're defining the functions but not calling them. Look at your indentation - the calls to withdraw(), deposit(), and balance() are only executed inside the else block. And without any arguments, to boot, which would cause an error if they were executed.
Related
I'm practicing with a simple roulette program. At this moment, I have a problem with balance input(), if I put it outside the function, the function betting() doesn't recognize it. But, if I put it inside, the function, the program asks me again to input the amount of money and it overwrites the amount of money after the bet.
How to avoid that, so the program asks me only once for input? This is my code:
import random
def betting():
balance = float(input("How much money do you have? $"))
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
betting()
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting()
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting()
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
betting()
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
Pass the balance as a function parameter to betting(). Then ask once in the choice() function
import random
def betting(balance):
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
return your_number
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting(balance)
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting(balance)
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
balance = float(input("How much money do you have? $"))
betting(balance)
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
You can ask for both at the same time and split the given string:
inp = input("State how much money you have and a number between 0 and 36 inclusive, separated by space: ")
bal, num = inp.split()
Python allocate a variable in the closest namespace.
This mean that balance is allocated in 'betting' namespace and will not be known outside 'betting'.
What you need is a global variable.
'global' mean that the variable must be allocated in the embracing namespace.
def betting():
global balance
print( balance)
def choice():
global balance
sel = input( ...)
if sel.lower() == 'y':
balance = int( input(">"))
betting()
choice()
Please note that you used 'choice' for 2 purposes. It's a function but it is also a variable. While it is possible, it is considered a bad habit.
Im trying to make an easy interface for a "bank", that is, a function choose() that lets the user choose the action they want, together with input values for the action if they are needed. The options so far included is printing the balance, deposit or withdraw money, and do the interest settlement. But I would like to add another option in the interface that lets the user see the last three changes made. How could I do that? Like for example they choose option 5 and they can see the changes like this:
+6105.0
-500000
+1110000
This is the code I got so far:
balance = 500
intrest_rate = 0.01
def deposit(amount):
global balance
balance= (balance+amount)
print(balance)
deposit(100)
print(balance)
def withdrawl(amount):
global balance
if amount>balance:
print("This amount will make you bankrupt:(")
else:
balance=(balance-amount)
print(f"You withdrew {amount} NOK from your balance , you know have {(balance)} NOK in your account")
withdrawl(150)
print(balance)
def calculating_intrest_rate():
global balance
global intrest_rate
if balance >= 1000000:
intrest_rate = 0.02
elif balance <= 1000000:
intrest_rate = 0.01
calculating_intrest_rate()
print(intrest_rate)
deposit(1000024)
calculating_intrest_rate()
print(intrest_rate)
def intrest_added_to_balance():
global intrest_rate
global balance
multiply = intrest_rate * balance
balance = (multiply+balance)
print(balance)
intrest_added_to_balance()
def choose():
print("""
1 - show balance
2 - deposit
3 - withdraw
4 - intrest settlement
5 - last changes
""")
choice = input("Please choose an action:")
if choice == "1":
print(balance)
elif choice == "2":
x= int(input("Please enter the amount you wish to deposit: "))
print(f"You added {x} NOK to your balance , you know have {(x) + (balance)} NOK in your account")
elif choice == "3":
y= int(input("Please enter the amount you wish to withdraw: "))
withdrawl(y)
elif choice == "4":
balance = balance + int((balance) * intrest_rate)
print (balance)
I have create functions to simulate ATM system, when asking the user to make deposit everything goes well but the problem is when the user make a withdraw. If the amount is greater than the balance I have the new balance in negative value. And need some help to correct this behavior.
My functions:
def show_balance(balance):
print(f"Current Balance: ${balance}")
def deposit(balance):
amount = input("Enter amount to deposit: ")
amount = float(amount)
result = balance + amount
return result
def withdraw(balance):
withdraw = input("Enter amount to withdraw: ")
withdraw = float(withdraw)
result = balance - withdraw
return result
Here is when using the functions:
# Display ATM menu to user
while True:
option = input("Choose an option: ")
if option == "1":
account.show_balance(balance)
elif option == "2":
balance = account.deposit(balance)
account.show_balance(balance)
elif option == "3":
balance = account.withdraw(balance)
account.show_balance(balance)
while True:
if balance < 0:
print("You do not have this money?")
break
else:
print("Please, provide a valid option")
Now when adding 50 using option "2" everithing works well. When the withdraw is < the balance (55) it just return a nagative value (-5). I want to print the massage: "You do not have this money?", but also keep the balance to the right amount (50 -55) => balance remain 50 and ask the user to try again.
#AKX -> Based on your precious advice, I have fixed the function doing the following:
def withdraw(balance):
withdraw = input("Enter amount to withdraw: ")
withdraw = float(withdraw)
if withdraw <= balance:
result = balance - withdraw
return result
elif withdraw > balance:
print("You do not have this money?")
return balance
I'm making a ATM-type program in which I have to ask the user if they want to deposit, withdraw, or check their balance in their savings or checking account, but only if the pin they enter is 1234. I've been instructed to use global variables and initialize savings and checking as 0. All of my functions are working properly, but when the program loops again the savings and checking balances are still 0, even when the user has just deposited money into either account. I'm not sure which part of my code is messing this up, but any help is greatly appreciated.
#Create global variables
Checking = 0
Saving = 0
def main():
pin_number = input("Please enter your pin number ")
stop = False
while not is_authorized(pin_number) and stop!= True:
if pin_number == "0":
stop = True
if pin_number == "1234":
stop = False
if stop != True:
while True:
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
def is_authorized (pin_number):
if pin_number == "1234":
return True
else:
return False
def display_menu():
print('1) Deposit')
print('2) Withdraw')
print('3) Check amount')
choice = int(input("Please enter the number of your choice: "))
return choice
def deposit():
depositing=str(input("Would you like to deposit into your savings
or checking? "))
if depositing == "savings":
depo = float(input("How much would you like to deposit? "))
new_savings = Saving + depo
print ("Your new balance is" +str (new_savings))
elif depositing == "checkings":
depo = input(int("How much would you like to deposit? "))
new_checking = Checking + depo
print ("Your new balance is" +str (new_checking))
def withdraw():
print ("Your savings account balance is " +str (Saving))
print ("Your checkings account balance is " +str (Checking))
withdrawing=str(input("Would you like to withdraw from your checking or savings? "))
if withdrawing == "checking":
withdraw = int(input("How much would you like to withdraw? "))
checking2= Checking - withdraw
print ("Your new balance is" +str (checking2))
elif withdrawing == "savings":
withdraw = int(input("How much would you like to withdraw? "))
savings2= Saving - withdraw
print ("Your new balance is" +str (savings2))
def check_balance():
checkbalance= input("Would you like to check your savings or checking? ")
if checkbalance == "savings":
print (Saving)
elif checkbalance == "checking":
print ("Your balance is $" +str (Checking))
main()
In order to modify values Saving and Checking in your functions you have to declare them global inside the function, not the use of global is not the most optimal, as far as I know, but it seems that is your task at hand. Your while loop can be simplified, by using while True and break. Along the way I found a few small things I touched up, I would also consider changing Saving to Savings since that is the keyword you are accepting as a response, makes things easier for you.
Checking = 0
Saving = 0
def main():
while True:
pin_number = input("Please enter your pin number ")
while pin_number not in ('0','1234'):
pin_number = input("Please enter your pin number ")
if pin_number == "0":
break
elif pin_number == "1234":
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
def is_authorized (pin_number):
if pin_number == "1234":
return True
else:
return False
def display_menu():
print('1) Deposit')
print('2) Withdraw')
print('3) Check amount')
choice = int(input("Please enter the number of your choice: "))
return choice
def deposit():
global Checking, Saving
depositing=str(input("Would you like to deposit into your savings or checking? "))
if depositing == "savings":
depo = float(input("How much would you like to deposit? "))
Saving += depo # use += here
print ("Your new balance is " +str (Saving))
elif depositing == "checking": # changed to checking
depo = int(input("How much would you like to deposit? "))
Checking += depo
print ("Your new balance is " +str (Checking))
def withdraw():
global Checking, Saving
print ("Your savings account balance is " +str (Saving))
print ("Your checkings account balance is " +str (Checking))
withdrawing=str(input("Would you like to withdraw from your checking or savings? "))
if withdrawing == "checking":
withdraw = int(input("How much would you like to withdraw? "))
Checking -= withdraw
print ("Your new balance is " +str (Checking))
elif withdrawing == "savings":
withdraw = int(input("How much would you like to withdraw? "))
Saving -= withdraw
print ("Your new balance is " +str (Saving))
def check_balance():
global Checking, Saving
checkbalance= input("Would you like to check your savings or checking? ")
if checkbalance == "savings":
print (Saving)
elif checkbalance == "checking":
print ("Your balance is $" +str (Checking))
main()
I have written this program and cant seem to figure out how to get the program to loop back to the beginning and ask the 'choice' option again.
The program runs fine, everything prints to the screen, even the part that asks if you would like another transaction, how do I get this to loop back?
Write ATM program. Enter account balance, print beginning balance.
ask for deposit or withdrawl, depending on selection, call function
to perform the action they wish, then print new balance. (Use iteration)
def withdraw():
amt = int(input("What amount to withdraw - multiples of $20: "))
print('New balance: $', balance - amt)
def deposit():
amt = int(input("How much are you depositing? "))
print('New balance: $',balance + amt)
def bal():
return(balance)
print ("Hello, Welcome to Python ATM.")
balance = float(65.01)
pin = int(input("please enter your account number (Any number:) "))
print('''Current balance: $''',balance)
choice = int(input('''
Please choose an option from the following:
1 - Withdraw
2 - Deposit
3 - Check Balance
4 - Exit: '''))
if choice == 1:
print(withdraw());
elif choice == 2:
print(deposit());
elif choice == 3:
print(bal());
more = input("Would you like another transaction? (y/n)")
Maybe you need a loop to repeat the choice :
while True:
print('''Current balance: $''',balance)
choice = int(input('''
Please choose an option from the following:
1 - Withdraw
2 - Deposit
3 - Check Balance
4 - Exit: '''))
if choice == 1:
print(withdraw());
elif choice == 2:
print(deposit());
elif choice == 3:
print(bal());
more = input("Would you like another transaction? (y/n)")
if more.lower() != 'y':
print("Goodbay")
break