Syntax Error, Cant figure out why(Line 17) - python

b. Create a program that simulates a simple savings account simulation. First ask the user for the initial balance (must be at least $100 and less than $400,000). As long as the user wants to continue allow them to make deposits and withdrawals – don’t overdraft! When the user is done, output the final balance.
(suggestion…use a menu something like:
1. Deposit
2. Withdrawal
3. Quit )
balance = int(input("Enter initial balance: $ "))
while balance <= 100 or balance >= 400000:
print ("Invalid Amount!")
balance = int(input("Ener valid amount: $ "))
deposit = 0
withdraw = 0
if balance >= 100 and balance <= 400000:
while ans != 3:
print("""
1. Deposit
2. Withdrawal
3. Quit
""")
ans = int(input("What would you like to do? Please enter the appropriate number. "))
if ans == 1:
deposit = int(input("\n How much would you like to deposit: $")
balance = balance + deposit
elif ans == 2:
withdraw = int(input("\n How much would you like to withdraw: $")
if (balance - withdraw) < 0
withdraw = int(input("\n Tried to withdraw too much! How much would you like to withdraw: $")
balance = balance - withdraw
elif ans == 3:
print("Your final balance is %d" %balance.)

You're missing a ) on the previous line, you want:
if ans == 1:
deposit = int(input("\n How much would you like to deposit: $"))
and an other one:
withdraw = int(input("\n How much would you like to withdraw: $"))
and then a tailing ::
if (balance - withdraw) < 0:
and another ) one further on:
if (balance - withdraw) < 0
withdraw = int(input("\n Tried to withdraw too much! How much would you like to withdraw: $"))
and then a space after your % (and get rid of the .):
print("Your final balance is %d" % balance)

You're missing a ')' on line 16.

Related

How to let user see the last changes made in the interface?

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)

How to return the right positive number in python whithou changing the initial variable?

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

Python error: "TypeError: input expected at most 1 arguments, got 3" (betting simulator)

I decided that I would write a code to simulate a betting game, where you guess the number the dice will land on. Eventually, the code became a full-blown simulator, with credit-card withdrawals and different dice types and stakes (don't ask me why there's a 4-sided dice, I doubt it's possible).
Anyway, I kept getting the same error. This is my code:
import random
from random import randint
diea = randint(1,4)
dieb = randint(1,5)
diec = randint(1,6)
jackpot = randint(1,30)
chance = randint (1,30)
cquit = "a"
bal = 10
credcard = 100
withdrawal = 0
deposit = 0
if jackpot == chance:
print("You won the jackpot of 10k!")
bal = bal + 10000
while cquit.lower() == "a":
print ("Your balance is $", bal)
print ("Your credit card balance is $", credcard)
choicea = input("Would you like to deposit / withdraw money - a for deposit, b for withdrawal, anything else to skip: ")
if choicea.lower() == "a":
deposit = int(input("How much would you like to deposit - you have $", bal," on you right now: "))
if deposit > bal:
print ("You do not have enough money - cancelling process")
else:
credcard = deposit + credcard
bal = bal - deposit
print ("Your balance is $", bal)
print ("Your credit card balance is", credcard)
if choicea.lower() == "b":
withdrawal = int(input("How much money would you like to withdraw - you have $", credcard," on your card"))
if withdrawal > credcard:
print ("Your card does not allow overdrafts - cancelling process")
else:
bal = withdrawal + bal
credcard = credcard - withdrawal
print ("Your balance is $", bal)
bet = int(input("How much would you like to bet?: "))
if bet > bal:
print ("You do not have enough money")
else:
diechoice = input("Choose die - A (1-4, x2), B (1-5, x3), C(1-6, x4): ")
if diechoice.lower() == "a":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - balance doubled")
bal = bal + bet
if guess > 4:
print ("That is above the die's capacity - bet cancelled")
if guess != diea:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
if diechoice.lower() == "b":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - tripling balance")
bet = bet*2
bal = bal + bet
if guess > 5:
print ("That is above the die's capacity - bet cancelled")
if guess != dieb:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
if diechoice.lower() == "c":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - quadrupling balance")
bet = bet*3
bal = bal + bet
if guess > 6:
print ("That is above the die's capacity - cancelling bet")
if guess != diec:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
elif diechoice.lower() != "a" and diechoice.lower() != "b" and diechoice.lower() != "c":
print ("Incorrect input - skipping bet")
cquit = input("a to continue, anything else to end: ")
if cquit.lower() == "a":
if bal == 0 and credcard == 0:
print ("ending program - you are bankrupt")
cquit = "b"
if bal > 0:
print ("continuing program")
print ("...")
print ("...")
print ("...")
else:
print ("ending program")
This is the error I get in the code when testing it. It happens when I enter a or b on the first input statement whenever it loops:
Traceback (most recent call last):
File "D:\FAKE NEWS\du.py", line 30, in <module>
withdrawal = int(input("How much money would you like to withdraw - you have $", credcard," on your card"))
TypeError: input expected at most 1 arguments, got 3
I've been reading other reports on the same errors but I'm too bad at Python to understand any of it.
input() is not like print(), you can't give it multiple arguments and expect it to concatenate them automatically in the prompt.
You have to do the string formatting yourself.
withdrawal = int(input("How much money would you like to withdraw - you have $%.2f on your card" % (credcard)))
deposit = int(input("How much would you like to deposit - you have $" + str(bal) + " on you right now: "))
and
withdrawal = int(input("How much money would you like to withdraw - you have $"+ str(credcard) + " on your card"))
You're passing three arguments to input, but it only takes one.
To put a number into a string, use str.format:
prompt = "You have ${} on your card.".format(dollars)
input(prompt)
This inserts the value of dollars as the first "replacement field" ({}), formatting it by calling str. You can add multiple replacement fields, and you can name them like so:
"x is {}, y is {}".format(x, y)
"x is {1}, y is {0}".format(y, x) # note switched arguments
"x is {x} y is {y}".format(x=x, y=y)
If you are using Python 3.6 or later, you can use an f-string instead:
current_balance = 100;
f"You have ${current_balance} on your card."
There are many other things you can do with the string-formatting syntax. This answer provides a quick look at a few of them, if you don't want to read the documentation.
change input line from
deposit = int(input("How much would you like to deposit - you have $", bal," on you right now: "))
to
deposit = int(input("How much would you like to deposit - you have $"+str(bal)+" on you right now: "))

In python, how do I update the balance when I withdraw money then deposit money?

I am creating an ATM using python code, and I need to create deposit and withdraw functions that behave just like an ATM would. Separately, the deposit and withdraw functions work. However, when I withdraw first then deposit, the balance does not update. Same thing when I deposit then withdraw.
Thank you and your help is much appreciated.
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
print("Amount left in your account: AED" + str(balance - withdraw))
return (balance - withdraw)
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
print("Amount left in your account: AED" + str(balance + deposit))
return (balance + deposit)
counter = counter + 1
withdraw()
deposit()
If I withdraw 17, the balance will be 583. However, when I deposit 12, the balance becomes 612, which is wrong it should be 595.
You are not changing the "balance" variable at all!
Your code should like something like:
balance = withdraw()
balance = deposit()
But there are multiple other problems with your code.
First of all you should not do that many casts. You have to convert your user input one time to a number, then just calculate everything with that type.
Your are using float and int. If you want to stuff with currency, you should use probably decimal (https://docs.python.org/2/library/decimal.html), because floating point arithmetic is not exact for some special cases (you need to round) and integer does obviously not provide floating point arithmetic.
Also your special 'while' usage does not fit common coding standards and makes your code hard to read. Better write one function to get user input and seperate it from the withdrawal() and deposit() logic.
EDIT: Since you seem to be a beginner, I will provide a minimal working solution.
import decimal
balance = 600
def get_user_input(action):
# Get user input and convert it to decimal type
return decimal.Decimal(input("Please enter amount to {} from your account: ".format(action)))
def withdraw():
amount = get_user_input("withdraw")
return balance - amount
def deposit():
amount = get_user_input("deposit")
return balance + amount
print("Your Balance is {} AED".format(balance))
balance = withdraw()
balance = deposit()
print("Your Balance is {} AED".format(balance))
You just forgot to save the new balance, you just print it out
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
while True:
withdraw = int(input("Enter amount to be withdrawn: "))
if withdraw > balance:
print("Error Amount not available in card.")
else:
new_balance = balance - withdraw
print("Amount left in your account: AED" + str(new_balance))
return (new_balance)
def deposit():
deposit = int(input("Enter amount to be deposited: "))
new_balance = balance + deposit
print("Amount left in your account: AED" + str(new_balance))
return (new_balance)
# This is the only place you HAVE to change for it to work
balance = withdraw()
balance = deposit()
Took the freedom to change it a bit, but most importantly, you should save the new balance.
I also suggest to make the integer conversion safer, by checking if it is an int before converting it to one.
withdraw_string = input("Enter amount to be withdrawn: ")
try:
withdraw_int = int(withdraw_string)
is_int = True
except ValueError:
print("INVALID INPUT")
is_int = False
if is_int == True:
In both your deposit() and widthdraw() functions, you are never actually touching the variable that holds your balance, that's why you don't see the change.
You have defined the variable balance yet at no point do you ever update that value with balance = balance - x. You are only printing the outcome of that math operation with str(balance + deposit), that code won't actually change your balance.
In order to change your balance you need to update that global variable with balance += widthdraw. But if you put that code in your code, you will get the following error:
UnboundLocalError: local variable 'balance' referenced before assignment
That is because in order to update a global variable from inside a function you need to use the global keyword so that a link is made to the global variable. Docs.
The following code now works, the two important lines are these:
balance -= withdraw
balance += deposit
That's how you are actually modifying the value in the balance variable instead of just seeing the output of the math operation.
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
global balance
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
balance -= withdraw
print("Amount left in your account: AED " + str(balance))
return (balance)
counter = counter + 1
def deposit():
global balance
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
balance += deposit
print("Amount left in your account: AED" + str(balance))
return balance
counter = counter + 1
withdraw()
deposit()
Disclaimer: You can most definitely remove your return statements from withdraw and deposit since they are essentially useless in this way of solving the problem. Why useless? Because the global variable balance gets modified inside the methods. The return statements would be useful if instead you modified the balance outside the methods. Something like this:
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
tmp_balance -= withdraw
print("Amount left in your account: AED " + str(tmp_balance))
return tmp_balance
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
tmp_balance += deposit
print("Amount left in your account: AED" + str(tmp_balance))
return tmp_balance
counter = counter + 1
balance = withdraw()
balance = deposit()
In this second way, you are manipulating the value of balance based on the returns that the methods provide you. The difference here is that when you call withdraw or deposit you are not actually carrying that out, you won't truly see it reflected until you commit to it with balance = withdraw() . There's a good advantage to doing it this way, which is making sure that no exceptions occur and that if withdraw or deposit completely finished at 100% , then you can commit the changes.
I decided to go a bit further into your code, since you seem to have a whole lot of castings of ints, floats and while loops.
Here's an example of how it could be approached, in case it helps to give anyone more ideas: (remember, there's no single path with code, we all code differently)
Use a decorator to handle int() castings. You can read about decorators here: https://www.python.org/dev/peps/pep-0318/. When you have repeated code (almost copy and paste), that's usually a sign to apply DRY (Don't Repeat Yourself). You can apply DRY by extracting the responsibility to a common function that you can call, or with awesome Python, use decorators. So decorators are nothing but functions, and you can "decorate" functions with them by simply putting #decorator_name. This just means that the decorator will be executed before the call to the decorated function.
I won't be casting to float because in your code you always cast the input to int(). If that's the case, then balance should never be a float.
Make a class called ATM that you can instantiate with a cash_available variable that is the cash in the ATM machine.
Remove fixed while loops (counter =2) and use instead one loop and let the user exit on command.
Extract the responsibility of getting the input for withdraw method, and let user decide whether they want to withdraw again.
Since you are using Python 3, apply f"" string format.
So now the code.
def exit_on_input_cast_error(func):
def wrapper(arg):
try:
return func(arg)
except ValueError as ex:
print("Exiting, bye.")
exit()
return wrapper
class ATM():
"""A simple atm machine"""
def __init__(self, balance):
self.cash_available = balance
#exit_on_input_cast_error
def withdraw(self):
'''Withdraws entered amount, until user exits'''
continue_withdraw = True
while continue_withdraw:
withdraw_amount = self._get_withdraw_input()
self.cash_available -= withdraw_amount
self.print_balance("left in")
withdraw_again = str(input("Would you like to withdraw another amount? (Y or N)"))
continue_withdraw = withdraw_again.lower() in ['1', 'y', 'yes']
self.print_bye()
#exit_on_input_cast_error
def _get_withdraw_input(self):
input_error = True
while input_error:
withdrawl = int(input("Enter the amount you want to withdraw (Press N to exit): AED "))
if (self.cash_available - withdrawl) < 0:
print("Error Amount not available in machine.")
input_error = True
elif (self.cash_available - withdrawl) > self.cash_available:
print("Error, you can't withdraw a negative amount.")
input_error = True
else:
input_error = False
return withdrawl
#exit_on_input_cast_error
def deposit(self):
input_error = True
while input_error:
depositing = int(input("Please enter the amount you want to deposit (Press N to exit): AED "))
if (self.cash_available + depositing) < self.cash_available:
print("You cannot deposit a negative amount.")
else:
input_error = False
self.cash_available += depositing
self.print_balance("now in")
self.print_bye()
def print_balance(self, custom_insert = 'in'):
print(f"Amount {custom_insert} your account: AED {self.cash_available}")
def print_bye(self):
print("Thank you for using our services today, bye.")
Let's go through it bit by bit.
The decorator is this.:
def exit_on_input_cast_error(func):
def wrapper(arg):
try:
return func(arg)
except ValueError as ex:
print("Exiting, bye.")
exit()
return wrapper
That's just the syntax for a decorator. The important part is the return func(arg). That's the function that will get caught. So this decorator is merely in charge of catching a ValueError exception, which can be thrown when you try to cast something like a int('a'). This decorator is meant to prevent a user trying to withdraw or deposit strings into the atm machine. Since it's code that you will use for both input of withdrawing or depositing, I have placed it as a decorator for ease of call (hello DRY principle).
Next up we have the class constructor. I hope you are familiar with classes, if you are not, there's a lot of links and documentation you can look up so you understand the difference between a class and a method like you had originally. The biggest advantage in this case is that you can have multiple atm's with different amount of cash in each. Or you could instantiate an ATM class, and give it configuration like language, or coin type. Stuff like that.
class ATM():
"""A simple atm machine"""
def __init__(self, balance):
self.cash_available = balance
That's such normal syntax for defining the class. The """A simple atm machine""" is the docstring so that when you call the classes .__doc__ you would get that in return.
Now to the good stuff.
#exit_on_input_cast_error
def _get_withdraw_input(self):
input_error = True
while input_error:
withdrawl = int(input("Enter the amount you want to withdraw (Press N to exit): AED "))
if (self.cash_available - withdrawl) < 0:
print("Error Amount not available in machine.")
input_error = True
elif (self.cash_available - withdrawl) > self.cash_available:
print("Error, you can't withdraw a negative amount.")
input_error = True
else:
input_error = False
return withdrawl
This method is meant to handle getting the input of the user. See how it's decorated with #exit_on_input_cast_error? That means that if the user puts in 'a' , then the program exits. That's because the int(...) cast will throw that ValueError exception, that the decorator catches. The method does the following in pseudocode:
while there's an error do the following:
Get the user input and cast it as an int.
Make sure the amount user has introduced matches the following criteria:
It is not more than the cash available in the atm.
It is not a negative number.
That's basically what this method does. It keeps asking the user to enter a valid input until either the user does so, or they exit by entering "N". And why do they exit when they enter "N". Because "N" is not an int, so when the cast occurs in this line:
withdrawl = int(input("Enter the amount you want to withdraw (Press N to exit): AED "))
A ValueError will be thrown by int(), that Exception is then caught by the handy decorator #exit_on_input_cast_error, which then prints "Bye" and exits for you. Cool right?
Next up is the actual withdraw method you had. The difference now is there is only one loop that continues to ask the user if he wants to keep withdrawing again once the action has finished. It's up to the user to either exit or withdraw again.
#exit_on_input_cast_error
def withdraw(self):
'''Withdraws entered amount, until user exits'''
continue_withdraw = True
while continue_withdraw:
withdraw_amount = self._get_withdraw_input()
self.cash_available -= withdraw_amount
self.print_balance("left in")
withdraw_again = str(input("Would you like to withdraw another amount? (Y or N)"))
continue_withdraw = withdraw_again.lower() in ['1', 'y', 'yes']
self.print_bye()
In pseudocode:
while the user wants to withdraw:
Get the user input
Check that the withdraw action does not result in 0 or negative number.
Print the balance
Ask the user if they want to withdraw again.
That's essentially what the method does. And it uses to new methods that are for printing message.
def print_balance(self, custom_insert = 'in'):
print(f"Amount {custom_insert} your account: AED {self.cash_available}")
def print_bye(self):
print("Thank you for using our services today, bye.")
These methods can be called and pass in custom parts of the message, like print_balance. They show the private class variable of the ATM class. In the withdraw method I have to point out that you can withdraw up to the point of reaching 0. The machine will let you try to keep withdrawing but it won't let you since there's 0 cash in it.
And last, the deposit method.
#exit_on_input_cast_error
def deposit(self):
input_error = True
while input_error:
depositing = int(input("Please enter the amount you want to deposit (Press N to exit): AED "))
if (self.cash_available + depositing) < self.cash_available:
print("You cannot deposit a negative amount.")
else:
input_error = False
self.cash_available += depositing
self.print_balance("now in")
self.print_bye()
As you can see, very simple and follows the same principle. Here's how you would call the actual methods:
atm_a = ATM(600)
atm_a.withdraw()
Here's an output of the code:
Enter the amount you want to withdraw (Press N to exit): AED 100
Amount left in your account: AED 500
Would you like to withdraw another amount? (Y or N)Y
Enter the amount you want to withdraw (Press N to exit): AED -1
Error, you can't withdraw a negative amount.
Enter the amount you want to withdraw (Press N to exit): AED 501
Error Amount not available in machine.
Enter the amount you want to withdraw (Press N to exit): AED 5
Amount left in your account: AED 495
Would you like to withdraw another amount? (Y or N)yes
Enter the amount you want to withdraw (Press N to exit): AED 5
Amount left in your account: AED 490
Would you like to withdraw another amount? (Y or N)no
Thank you for using our services today, bye.
If you want to withdraw and deposit:
atm_a = ATM(600)
atm_a.withdraw()
atm_a.deposit()
Here's output of the code:
Enter the amount you want to withdraw (Press N to exit): AED 500
Amount left in your account: AED 100
Would you like to withdraw another amount? (Y or N)no
Thank you for using our services today, bye.
Please enter the amount you want to deposit (Press N to exit): AED -1
You cannot deposit a negative amount.
Please enter the amount you want to deposit (Press N to exit): AED 1000
Amount now in your account: AED 1100
Thank you for using our services today, bye.
Notice how you can only deposit once and then it exists. That's because I didn't implement that, since I already did that for withdraw. Anyone can just replicate it in the deposit if they want.
I hope this wasn't too much and that I managed to explain it. There's loads of things than can be added to this:
Test cases
Difference between cash in ATM physically and balance of the user's account
In withdrawing, knowing if you have the right amount of bills to give the desired amount
...etc
You are not changing the balance variable, you are only returning the value with the added or reduced deposit or withdraw.
Try changing your code so that it saves the new balance before returning it. So instead of:
print("Amount left in your account: AED" + str(balance - withdraw))
return (balance - withdraw)
Try:
balance = (balance - withdraw)
print("Amount left in your account: AED" + str(balance))
return balance
Then do the same with the deposit function.
Your new code:
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
balance = (balance - withdraw)
print("Amount left in your account: AED" + str(balance))
return balance
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
balance = (balance + deposit)
print("Amount left in your account: AED" + str(balance))
return balance
counter = counter + 1
withdraw()
deposit()
I agree with #Chetan Ranpariya's suggestion, you haven't change your balance variable in your code for both function. You can change your balance variable using the expression balance += <increase amount>, balance -= <decrease amount> or balance = balance + <increase amount>, etc.
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
print("Amount left in your account: AED" + str(balance - withdraw))
return (balance - withdraw)
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
print("Amount left in your account: AED" + str(balance + deposit))
return (balance + deposit)
counter = counter + 1
balance = withdraw()
balance = deposit()

What am i doing wrong in this attempt at an infinite loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to make a code for my python class and i'm making a wallet management system basic. but i cant get this infinite loop to work. What am i doing wrong?
def main():
# Initial balance
balance = input ('Wallet balance: ')
# This constructs the infinite loop
while true:
# Initial balance
balance = input ('Wallet balance: ')
# Withdraw amount from wallet balance
withdraw= input ('Withdraw amount: ')
#If there is no balance to withdraw from
if balance < 1:
print ('You have no funds to withdraw.')
# Withdraw process and new balance display
if balance > 0:
new = balance - withdraw
print ('Your new balance: '), new
main()
Fixed it for you, it had a few errors
True must be capitalized in Python
If you are passing an int into a str you need to cast the int as a str
Also, I'm not sure why what you're using the main function for? It doesn't pass the initial value into the infinite loop and seems redundant.
def main():
# Initial balance
balance = input ('Wallet balance: ')
# This constructs the infinite loop
while True:
# Initial balance
balance = input('Wallet balance: ')
# Withdraw amount from wallet balance
withdraw= input('Withdraw amount: ')
#If there is no balance to withdraw from
if balance < 1:
print('You have no funds to withdraw.')
# Withdraw process and new balance display
if balance > 0:
new = balance - withdraw
print('Your new balance: ' + str(new))
main()
However, I'm assuming you're trying to build a functional wallet that can withdraw and deposit. I'm not sure how comfortable you are with python and class construction, but I built a fully functional wallet for you to check out and learn from.
class Wallet:
#Grab the initial balance in the account
def __init__(self, initial_balance):
self.balance = initial_balance
#method that deposits funds to the balance
def deposit(self, deposit_amount):
self.balance += deposit_amount
#method that attempts to withdraw from the balance
def withdraw(self, withdraw_amount):
if withdraw_amount <= self.balance:
self.balance -= withdraw_amount
else:
print("Insufficient funds. You have " + str(self.balance) + " in your account. Please deposit more or withdraw less.")
#display the balance
def display_balance(self):
print("The current balance in the account is " + str(self.balance))
print("-----")
#Check if this module is the one currently being run
if __name__ == "__main__":
#Ask user for initial balance
initial_balance = int(input("Initial balance in account: "))
#initiate the class, passing the initial balance
wallet = Wallet(initial_balance)
wallet.display_balance()
while True:
#Pick an option to withdraw, deposit or exit
print("1: Deposit funds")
print("2: Withdraw funds")
print("3: Exit")
type = int(input("Please select an option (1, 2 or 3): "))
if type == 1:
deposit_amount = int(input("Please specify amount to deposit: "))
wallet.deposit(deposit_amount)
wallet.display_balance()
elif type == 2:
withdraw_amount = int(input("Please specify amount to withdraw: "))
wallet.withdraw(withdraw_amount)
wallet.display_balance()
elif type == 3:
break
else:
print("Invalid selection, please type either 1, 2 or 3")
I don't have python3, but this worked in python2 and I added the parentheses around the print-statement after.
def main():
# Initial balance
balance = int(input('Wallet balance: '))
# This constructs the infinite loop
while True:
# Withdraw amount from wallet balance
withdraw = int(input('Withdraw amount: '))
#If there is no balance to withdraw from
if balance < 1:
print ('You have no funds to withdraw.')
# Withdraw process and new balance display
if balance > 0:
new = balance - withdraw
print ('Your new balance: ', new)
main()

Categories

Resources