I want to make electricity payments by reducing the balance in the data list with bills in the electricity list.
data = [{"norek":"932012042", "name":"Ahmad Sujagad", "balance":5000000},
{"norek":"932012052", "name":"Basuki Pepeh", "balance":4000000},
{"norek":"932012099", "name":"Bambang Gentolet", "balance":3500000}]
data_ele =[{"noseri":"7932392", "name":"Ahmad Sujagad", "bill":320000},
{"noseri":"7932384", "name":"Basuki Pepeh", "bill":250000},
{"noseri":"7932345", "name":"Bambang Gentolet", "bill":180000}]
When I do transactions, the balance is reduced, but when I choose option 1, why is it not reduced?
print("1.Electric\n2.Water")
option = int(input("Please Select Menu :"))
if option == 1:
print("total bill : ",dlist['bill'])
bayar = input("Are You Sure You're Paying? (Y/T)")
if bayar == "Y" or bayar == "y":
print("No Seri : ",dlist['noseri'],"\n","name :",dlist['name'])
print("your remaining balance :",duser['balance']-dlist['bill'])
elif bayar == "T" or bayar == "t":
print("Payment Cancelled")
Console:
Please Select Menu :1
total bill : 320000
Are You Sure You're Paying? (Y/T)y
No Seri : 7932392
name : Ahmad Sujagad
your remaining balance : 4680000
when I check back in the option one, the balance is not reduced:
if option == 1:
print("your remaining balance :",duser['balance'])
Console:
Please Select Menu :1
your remaining balance : 5000000
In the following line:
print("your remaining balance :",duser['balance']-dlist['bill'])
...you are only showing the result, but you are not updating the balance. Replace this line with:
duser['balance'] -= dlist['bill'] # update!
print("your remaining balance :", duser['balance']) # show new balance
Related
I decided to make a code in Python that is like an ATM Machine, and Everything works very well, you can check your balance, extract or add money,and change the PIN code. But when I change the PIN code i tried to assign the "changed_pin_code" variable to the "real_pin_code" variable,and it doesen't work, the PIN code remains the same. If you could give me some ideas on how I could solve the problem, or improve my code, that would be fantastic.
I am at the beggining with coding, and I am doing this so I can test my knowledge.
I left the code below.
def atm_machine():
code = input("Enter yout PIN code:")
pin_code = int(code)
real_pin_code = 4137
balance = 10000
if pin_code == real_pin_code:
print("""
ATM
1)Check Balance
2)Add money
3)Extract money
4)Change PIN code\n""")
number_select = int(input("Select a number:"))
if number_select > 4 and number_select == 0:
print("You must select a number between 1 and 4!")
atm_recall()
if number_select == 1:
print("Your current balance is:", balance, "$")
atm_recall()
if number_select == 2:
money_add = int(input("Enter amount of money you want to add:"))
new_money = balance + money_add
print("Your current balance is:", new_money, "$")
atm_recall()
if number_select == 3:
money_extract = int(input("Enter the amount of money you want to extract:"))
if money_extract > balance:
print("Insufficent fund")
atm_recall()
if money_extract <= balance:
remained_money = balance - money_extract
balance = remained_money
print("Your current balance is:", remained_money, "$")
atm_recall()
if number_select == 4:
measure_pin = 9999
changed_pin_code = int(input("Enter new PIN code:"))
if changed_pin_code == real_pin_code:
print("You can't enter the same PIN code:")
print("Wait for yout card!")
atm_recall()
if changed_pin_code > measure_pin:
print("PIN code must be formed of 4 digits!")
print("Wait for your card")
atm_recall()
else:
real_pin_code = changed_pin_code
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
atm_recall()
else:
print("PIN code inccorect!")
print("Wait for your card!")
def atm_recall():
question = str(input("To make another action, type \"Y\",else, type\"N\" "))
if question == "Y":
result = atm_machine()
return result
if question == "N":
print("Good Bye!")
print("Wait for your card!")
atm_machine()
The problem you are currently facing is because at end of each option you call atm_recall function, in which if the user selects the 'Y' option, it calls the atm_machine function which whenever called starts with real_pin_code set to 4137.
Solution:
As already mentioned by others, in comments what you should rather do is get rid of the recursion as it uses up a lot of memory and fills up the call stack on each function call. So a refactored approach would be something like this:
real_pin_code = 4137
balance = 10000
while True:
code = input("Enter yout PIN code:")
pin_code = int(code)
if pin_code == real_pin_code:
print("""
ATM
1)Check Balance
2)Add money
3)Extract money
4)Change PIN code\n""")
number_select = int(input("Select a number:"))
if number_select == 1:
print("Your current balance is:", balance, "$")
elif number_select == 2:
money_add = int(input("Enter amount of money you want to add:"))
balance = balance + money_add
print("Your current balance is:", balance, "$")
elif number_select == 3:
money_extract = int(input("Enter the amount of money you want to extract:"))
if money_extract > balance:
print("Insufficent fund")
else:
remained_money = balance - money_extract
balance = remained_money
print("Your current balance is:", remained_money, "$")
elif number_select == 4:
measure_pin = 9999
changed_pin_code = int(input("Enter new PIN code:"))
if changed_pin_code == real_pin_code:
print("You can't enter the same PIN code:")
print("Wait for yout card!")
elif changed_pin_code > measure_pin:
print("PIN code must be formed of 4 digits!")
print("Wait for your card")
else:
real_pin_code = changed_pin_code
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
else:
print("You must select a number between 1 and 4!")
else:
print("PIN code inccorect!")
print("Wait for your card!")
question = str(input("To make another action, type \"Y\",else, type\"N\" "))
if question == "N":
print("Good Bye!")
print("Wait for your card!")
break
Changes:
I took real_pin_code out of the loop, so its value doesn't reset at each iteration.
Also, for the same reason I took balance out of the loop and made the changes to balance itself rather than declaring a new variable new_money.
Also, as a good programming practice I changed a lot of if statements to elif and else where the conditions were exclusive of each other.
Better Approach:
A better approach, as already highlighted by others would be to use class where you would initialize an ATMMachine object with all the required details. However the approach you choose, mostly all the logic would remain the same except some refactoring and specific methods for each task.
I'm not sure if it's a best way to do it, but I would create a txt file with atm pin which You could read in the beggining to take pin code and write it when You want to change it. Something like this:
def atm_machine():
code = input("Enter yout PIN code:")
pin_code = int(code)
real_pin = open("code.txt", "r")
real_pin_code = int(real_pin.read())
Here I already have a txt file with some code created in program folder so python could read it, and here I'm saving new pin to same txt file:
else:
real_pin = open("code.txt", "w")
real_pin.write(str(changed_pin_code))
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
atm_recall()
Hope this helps anyhow.
I have created a simple python program that lets users drive different cars. The user will enter their full name, address, and phone number. The user will then be asked which car they wish to drive, with a maximum of five selected cars. The cars have set prices and a total bill will be added up at the end of the program, however, I am currently unable to find a solution to work out the total cost for the user. The program also asks the user how many laps of the race they wish to perform in the car, I have already worked out how to display the total cost of the laps, but need it added to the total cost somehow. Thanks!
Code
cars_list = ["Lamborghini", "Ferrari", "Porsche", "Audi", "BMW"]
cars_prices = {"Lamborghini":50, "Ferrari":45, "Porsche":45, "Audi":30, "BMW":30}
laps_cost = 30
final_cost = []
final_order = {}
cust_num_cars = int(input("Please enter the number of cars you want to drive in this session: "))
while cust_num_cars > 5:
cust_num_cars = int(input("You can only drive a maximum of five cars! Please try again.\n Enter cars: "))
for index in range(cust_num_cars):
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", {select_cars})
final_cost.append(cars_prices[select_cars])
if select_cars not in cars_list:
print("\n",{select_cars}, "is not in the available list of cars to drive!")
cust_name = input("\nPlease enter your full name: ")
cust_address = input("Please enter your full address: ")
cust_phone_num = int(input("Please enter your mobile phone number: "))
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
final_cost.append(cars_prices[add_laps])
sum = num_of_laps * laps_cost
else:
print("\nYou have selected no additional extra laps.")
print("Total laps cost: £",final_cost)
print("\n----Order & Billing summary----")
print("Customer Full Name:", cust_name)
print("Customer Address:", cust_address)
print("Customer Phone Number", cust_phone_num)
print("Total cost", final_cost.append(cars_prices))
I have tried everything I know in my little experience with Python to work out a final cost. I have worked out the total cost for the number of laps, but can't work out how to add that to the cost of the selected cars and then display a total cost.
First, you can't use a for-loop because when you select a car that isn't in the possibilities you have lost an iteration, use a while loop
# final_cost renamed to car_cost
while len(car_cost) != cust_num_cars:
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", select_cars)
car_cost.append(cars_prices[select_cars])
else:
print("\n", select_cars, "is not in the available list of cars to drive!")
Then use sum() for the cars cost and add to the laps cost
num_of_laps = 0
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
else:
print("\nYou have selected no additional extra laps.")
total = num_of_laps * laps_cost + sum(car_cost)
print("Total price:", total)
To calculate the total cost, you can use the built-in sum() function, which takes an iterable (like a list) and returns the sum of all its elements. In your case, you can use it to add up all the prices of the cars that the user selected:
total_cost = sum(final_cost)
Then you can add the cost of the laps to the total cost. In your code, the variable sum holds the total cost of the laps. You can add that to the total_cost variable:
total_cost += sum
Hi friend in this program its better to add all of your costs in one variable.
in a list your list's elements are not adding together,
but with variables you can add your cost every time you get a cost like this:
cost_sum = 0
cost = input("Enter a cost: ")
cost_sum += cost
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")
please can anyone check my code and correct me why I am unable to enter if statement when I was given option input==3 and option input==4.
import sys,os,math
Account_balance= int(25000)
print('*** WELCOME TO SBI BANK NAKKALAGUTTA ***')
givenpin=input('Enter The 4 Digit Pin Number ')
if givenpin =='0351':enter code here
print('welcome MR.Anudeep RAO')
else:
print('unauthorized access try again')
sys.exit()
print('your A/C number is: 10987xxxxxx')
print("### choose an option below ###")
print("""
1) Balance
2) Withdraw
3) Deposit
4) Quit
""")
option = int(input("Enter option:"))
if option == 1:
print('your Account balance is' +' '+ str(int(Account_balance)) +'Rs/-')
elif option == 2:
input_to_Withdraw = int(input("enter amount to withdraw "))
if input_to_Withdraw > 25000:
print("Insufficient Funds in Your A/C")
elif input_to_Withdraw < 25000:
present_balance = (Account_balance - input_to_Withdraw)
print('collect cash and available balance is ' + str(int(present_balance)))
if option == 3:
Input_to_Deposit = int(input("enter amount to deposit into A/C "))
print('deposited balance is:')
print(Account_balance +Input_to_Deposit)
if option == 4:
print('Transaction complete leave bank safely Bye:')
The if option == 3: and if option == 4: cases are deep inside the elif option == 2: case. Since you don't reset the value of option anywhere, I assume this is a mistake.
Fix the indentation of these two cases so your code has a chance to follow these paths. They should be at the same indentation level as elif option == 2:.
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()