I'm trying to get Python to print every user input on a while loop. Essentially the user enters a value, then is asked again and again for a value until user decides to stop entering values. The code prints the sum of the values but also each individual value inputted.
I managed to get everything working except printing each individual value. Any help is really appreciated!
another = True
init_bal = 1000
deposit = 0
while another:
another += 1
deposit += int(input("Enter amount: "))
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
break
another = True
init_bal = 1000
deposit = 0
toatl_deposits = []
while another:
another += 1
deposit += int(input("Enter amount: "))
toatl_deposits.append(deposit)
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
print('following are list of user inputs: ')
for i in toatl_deposits:
print(f'${i}')
break
Try this,
from datetime import datetime
init_bal = 1000
deposit = 0
transactions = []
while True:
deposit += int(input("Enter amount: "))
print(f'${deposit} deposited!')
transactions.append({'time': datetime.now(), 'amount': deposit})
try:
another = int(input("Make another deposit (Yes=1, No=any)?"))
except:
break
if another != 1:
break
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print('Your transactions history:')
for transaction in transactions:
print('Deposited $' + str(transaction['amount']) + ' at ' + str(transaction['time']))
print(f'Your final balance is ${init_bal + deposit}.')
If you write this code by yourself you could understand to easily break it down and print out like this.
another = True
init_bal = 1000
deposit = 0
while another:
another += 1
amount = input("Enter amount: ")
deposit += int(amount)
print("Deposit Amount = " , amount)
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
break
Related
I was following along with a youtube video to a ATM using python and I got expected expression. I dont know how to fix it. line 32, 37 and 40.
enter image description here
You can't have an elif after an else. This is because else will capture all the remaining cases. Indentation, meaning spaces or tabs before the line is very important in Python.
Here is what I think you meant to write:
balance = 1000
print("""
Welcome to Dutch Bank
Choose Transaction
1) BALANCE
2) WITHDRAW
3) DEPOSIT
4) EXIT
""")
while True:
option = int(input("Enter Transaction"))
if option == 1:
print ("Your Balance is", balance)
anothertrans = input("Do You Want to make another Transaction? Yes/No: ")
if anothertrans == "YES":
continue
else:
break
elif option == 2:
withdraw = float(input("Enter Amount To Withdraw"))
if (balance > withdraw):
total = balance - withdraw
print("Success")
print("Your New Balance is: ",total)
else:
print("Insufficient Balance")
elif option == 3:
deposit = float(input("Enter Amount To Deposit"))
totalbalance = balance + deposit
print("Sucess")
print("Total Balance Now is: ", totalbalance)
elif option == 4:
print("Thank You ForBanking With Dutch Bank")
exit()
else:
print ("No selected Transaction")
Hi i am albert i am learning python, in this block of code i wrote i intend it to print the total, but the input statements just keep going in a loop
print("this program prints your invoice")
while True:
ID = input("item identification: ")
if ID == "done":
break
if len(ID) < 3:
print("identification must be at least 3 characters long")
exit(1)
break
try:
Quantity = int(input("quantity sold: "))
except ValueError:
print("please enter an integer for quantity sold!!!")
exit(2)
if Quantity <= 0:
break
print("please enter an integer for quantity sold!!!")
exit(3)
try:
price = float(input("price of item"))
except ValueError:
print("please enter a float for price of item!!")
exit(4)
if price <= 0:
print("please enter a positive value for the price!!!")
exit(5)
break
cost = 0
total = cost + (Quantity*price)
print(total)
I think you need this
cost = 0
total = cost + (Quantity*price)
print(total)
to be inside the while loop. Else, skip the loop completely.
Try this:
print("This program prints your invoice")
total = 0
more_to_add = True
while more_to_add == True:
ID = input("Item identification: ")
if len(ID) < 3:
print("Identification must be at least 3 characters long")
continue
try:
Quantity = int(input("Quantity sold: "))
except ValueError:
print("Please enter an integer for quantity sold!!!")
continue
if Quantity <= 0:
print("Please enter an integer for quantity sold!!!")
continue
try:
price = float(input("Price of item: "))
except ValueError:
print("Please enter a float for price of item!!")
continue
if price <= 0:
print("Please enter a positive value for the price!!!")
continue
total = total + (Quantity*price)
answer = input("Want to add more? (Y/N)" )
if answer == 'Y':
more_to_add = True
else:
more_to_add = False
print(total)
The deposit function and the withdraw function doesn't work. After populating the accounts, I can select D or W menu options and input any number without causing the program to crash or causing an error. The program seems it is working correctly but when you check the balances using the S option, they are not updated.
Names=[]
accountnumbers=[]
balance=[]
def populatelist():
position=0
while(position<=2):
yourname= str(input("Please enter a name: "))
Names.append(yourname)
account = int( input("Please enter an account number: " ))
accountnumbers.append(account)
totalbalance = int( input("Please enter a balance: "))
balance.append(totalbalance)
position = position + 1
##################################### DEPOSIT FUCNTION
def deposit(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
#################################### WITHDRAW FUNCTION
def withdraw(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def findingaccount(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def menuoptions():
print ("**** MENU OPTIONS ****")
print ("Type P to populate accounts")
print ( "Type S to search for account")
print ("Type E to exit")
print ("Type D to deposit Amount")
print ("Type W to withdraw Amount")
choice = str(input("Please enter your choice: "))
return choice
response=""
while response!= "E":
response = menuoptions()
if response=="P":
populatelist()
########################### Deposit OPTION
elif response=="D":
searchaccount = int(input("Please enter the account number to add deposit: "))
foundtheposition = deposit(searchaccount)
money = int(input("Please enter the amount to be deposited: "))
money + (balance[foundtheposition])
########################### WITHDRAW OPTION
elif response=="W":
searchaccount = int(input("Please enter the account number to withdraw: "))
thenumber = withdraw(searchaccount)
withdraw = int(input("how much for withdraw"))
withdraw - (balance[thenumber])
if (balance[thenumber]) < withdraw :
print("ERROR: Not enough balance")
elif response=="S":
searchaccount = int(input("Please enter the account number to search: "))
foundaposition = findingaccount(searchaccount)
if ( foundaposition == -1 ):
print ("The account number not found!")
else:
print ("Name is:" + str( Names[foundaposition]))
print (str(Names[foundaposition]) + " " + "account has the balance of :" +str(balance[foundaposition]))
elif response=="E":
print ("Thank you for using the program.")
print ("Bye")
exit
else:
print ("Invalid choice. Please try again!")
You have logic error.
Just change
money + (balance[foundtheposition])
to
balance[foundtheposition] = balance[foundtheposition] + money
or using short-hand operator like
balance[foundtheposition] += money
Same for
withdraw - (balance[thenumber])
Cheers ...
Your deposit scenario needs to add the amount into the selected account:
balance[thenumber] += money
Fair warning there are other errors in your program besides the accounts not updating.
I am trying to create a cash register program. My objective is for all the products be added and the final price be found. How can I reach this goal without knowing the values previously? Below is my code. Thanks in advance for any help it is greatly appreciated
responses = {}
polling_active = True
print("Welcome to the cash register. Insert your product name and price to be able to calculate your final total")
total = 0
while polling_active:
product = input("\nProduct Name: ")
total += float(input("Price: "))
responses[product] = total
repeat = input("Is this your final checkout? (Yes/No)")
if repeat == 'no':
polling_active = True
elif repeat == 'No':
polling_active = True
elif repeat == 'Yes':
polling_active = False
elif repeat == 'yes':
polling_active = False
else:
print("That operation is invalid")
print("\n---Final Checkout---")
for product, price in responses.items():
print(product + " is $" + str(total))
print("\n---Total Price---")
print("Store Price is: ")
print("$" + str(total))
print("\n---Tax Price---")
print("Your price with tax is: ")
total = total * 1.13
print("$" + "{0:.2f}".format(float(total)))
print("\nThank you for shopping with us! Have a great day!")
I understand the with my current code, total will not allow me to add any products but that is just currently a place holder
Here is the code that you need:
responses = {}
polling_active = True
print("Welcome to the cash register. Insert your product name and price to be able to calculate your final total")
while polling_active:
product = input("\nProduct Name: ")
price = float(input("Price: "))
responses[str(product)] = price
repeat = raw_input("Is this your final checkout? (Yes/No)")
if repeat.lower() == 'no':
polling_active = True
elif repeat.lower() == 'yes':
polling_active = False
else:
print("That operation is invalid")
print("\n---Final Checkout---")
for product, price in responses.items():
print(product + " is $" + str(price))
print("\n---Total Price---")
print("Store Price is: ")
total= sum(responses.values())
print("$" + str(total))
print("\n---Tax Price---")
print("Your price with tax is: ")
total = total * 1.13
print("$" + "{0:.2f}".format(float(total)))
print("\nThank you for shopping with us! Have a great day!")
Output:
integer:
float:
I've been having some trouble with Else and Elif statements in Python 3.3.3 lately.
Here's my code:
# ATM was programmed by Jamie Mathieson
# introduction
sleep (1)
print ("-----------------------------------------------")
print ("\n ATM ")
print ("\n-----------------------------------------------")
sleep (3)
print ("\nWelcome to ATM. ATM is a mathematical system that handles data.")
sleep (5)
print ("\n Your ATM card has is being inserted. Please wait...")
sleep (3)
print ("Your ATM card has been inserted.")
sleep (5)
print ("Type 'options' to view available commands.")
# variables
balance = print("Balance £", money)
money = 200
options = ("Options: 1) Withdraw <amount> 2) Deposit <amount> 3) Balance 4) Exit")
# statements
option=int(input("Please enter an option: "))
if Option==1:
print("Balance £", money)
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif: Withdraw>money
print("No Balance Remaining")
else:
print("Withdraw canceled.")
if Option==3:
print("Balance £", money)
Deposit=float(input("Please enter the amount of money you would like to deposit: £ "))
if Deposit>0:
newbalance=(money+Deposit)
print("New Balance: £",newbalance)
else:
print("Deposit canceled.")
if Option==4:
print("ATM is ejecting your card. Please wait...")
sleep(5)
exit()
The error I'm getting is "invalid syntax" and it highlights both the Else and Elif statements. What is it that I'm doing wrong?
You have to put the : at the end, and correct the identation.
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif Withdraw>money:
print("No Balance Remaining")
else:
print("Withdraw canceled.")
There are several issues with the code. As #Daniel pointed out, your indentation must be corrected. Also, your condition for the elif block is placed after the colon.
Beyond that, you're assigning the user's response to a variable called option and then writing conditions on Option. Those are two different things.
Finally balance = print("Balance £", money) is going to throw an error. It looks like you're trying to define balance as a function that will print "Balance £" followed by the balance amount. If so, you could do something like this:
balance = lambda x: print("Balance £{}".format(x))
Edit: To answer your question re: sleep, use
from time import sleep
while True:
# Reading id from user
id = int(input("\nEnter account pin: "))
# Loop till id is valid
while id < 1000 or id > 9999:
id = int(input("\nInvalid Id.. Re-enter: "))
# Iterating over account session
while True:
# Printing menu
print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ")
# Reading selection
selection = int(input("\nEnter your selection: "))
# Getting account object
for acc in accounts:
# Comparing account id
if acc.getId() == id:
accountObj = acc
break
# View Balance
if selection == 1:
# Printing balance
print(accountObj.getBalance())
# Withdraw
elif selection == 2:
# Reading amount
amt = float(input("\nEnter amount to withdraw: "))
ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ")
if ver_withdraw == "Yes":
print("Verify withdraw")
else:
break
if amt < accountObj.getBalance():
# Calling withdraw method
accountObj.withdraw(amt)
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalance()) + " n")
print("\nPlease make a deposit.");
# Deposit
elif selection == 3:
# Reading amount
amt = float(input("\nEnter amount to deposit: "))
ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ")
if ver_deposit == "Yes":
# Calling deposit method
accountObj.deposit(amt);
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
break
elif selection == 4:
print("nTransaction is now complete.")
print("Transaction number: ", random.randint(10000, 1000000))
print("Current Interest Rate: ", accountObj.annualInterestRate)
print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12)
print("Thanks for choosing us as your bank")
exit()
# Any other choice
else:
print("That's an invalid choice.")
# Main function
main()