I'm a beginner to Python and programming, and I'm trying to make a simple piggy bank that will be able to deposit or withdraw pennies, nickels, dimes, and quarters. I don't know how to loop the code or how to store the data if I enter a coin to be able to keep adding to the total number of coins in the bank. I can only do it so it runs and tells me if I add, for example, 100 pennies, that my bank has 100 pennies. but then it resets. How do I do this? my code is probably awful but here's what I have so far based off my current knowledge of python (added empty parts like the "return" and pennies_previous so anyone reading can understand my thought process, and the withdrawstep() function has not been added yet):
print "Welcome to the Piggy Bank!"
def depositstep():
deposit = raw_input("What would you like to deposit? (P for pennies, N for nickels, D for dimes, Q for quarters): ").upper()
if deposit == 'P':
pennies_previous =
pennies_instance = raw_input("How many pennies would you like to deposit?: ")
pennies_total = int(pennies_instance) + pennies_previous
print "There are %s pennies in your bank"% (pennies_total)
return execute()
elif deposit == 'N':
N = raw_input("How many nickels would you like to deposit?: ")
return
elif deposit == 'D':
D = raw_input("How many dimes would you like to deposit?: ")
return
elif deposit == 'Q':
Q = raw_input("How many quarters would you like to deposit?: ")
return
else:
return "Sorry. Please Type P for pennies, N for nickels, D for dimes, or Q for quarters."
def execute():
exc = raw_input("Would you like to deposit or withdraw money? (D for deposit, W for withdraw): ").upper()
if exc == 'D' or exc == 'DEPOSIT':
return depositstep()
elif exc == 'W' or exc == 'WITHDRAW':
return withdrawstep()
else:
return "Sorry. Please type D for deposit or W for withdrawal."
print execute()
You should store your total amount of pennies in the original variable.
pennies_previous= int(pennies_instance) + pennies_previous then the amount of pennies will be stored there.
If you are looking to make the bank continue to store the value of the bank for each session, then you are going to want to save the bank's value to a file. You could do it like this:
1. First, make a file with a name like bankvalue.txt.
2. Then, add these lines before every return:
value = open(bankvalue.txt, 'w') # that opens your bankvalue.txt file in write mode
value.write('\n'pennies_previous) #You should use the answer above for the pennies_previous
value.close() #saves the file
3.Then, in order to tell a person their balance you would use the readline() function
I hope that was what you were looking for
I would use a python dictionary instead of variables:
do so as:
bank = {'pennies':0, 'nickles':1, 'dimes':0, 'quarter':0}
to increase either of those you do
bank['pennies'] += int(pennies_instance) # not need the pennies_previous
Then you need to write that to a file which you could do:
f = open('filename','w')
f.write(bank.items())
f.close
But that don't preserve the python structure. But you can use json module, which is simple as:
import json
f = open('filename','wb')
json.dump(bank,f)
f.close()
And at the start of the script you need to fetch the data from the file, you do this with
f = open('bank.dat','rb')
bank = json.load(f)
It would look like this:
import json
f = open('bank.dat','rb')
bank = json.load(f)
f.close()
## you code goes here.
f = open('bank.dat','wb')
json.dump(bank,f)
f.close()
There are some other problems in your code that should be addressed too.
1) In the 'else' part of your code, if the user inputs the wrong letter it terminates, instead it should call the function again.
2) You don't need to return a string and print it in the 'print execute()', you could just print it in place and don't return anything.
Related
I would like to be able to take the test scores the user inputs and write to an external text file. Then have the application read off the values from the and calculate the average. However, I am unsure as to how to implement the python syntax within the loop and the functions. I've attempted to utilize my resources to get a better idea of how to do this, but I've been having some trouble understanding how python handles external files. In addition, would using append be better than write in this scenario?
Current Syntax:
def testAvgCalculation():
#Variables
total = 0
total_quiz = 0
while True:
#User Input and Variable to stop loop
inpt = input("Enter score: ")
if inpt.lower()== 'stop':
break
#Data Validation
try:
if int(inpt) in range(1,101):
total += int(inpt)
total_quiz += 1
else:
print("Score too small or Big")
except ValueError:
print("Not a Number")
return total, total_quiz
def displayAverage(total, total_quiz):
average = total / total_quiz
print('The Average score is: ', format(average, '.2f'))
print('You have entered', total_quiz, 'scores')
#Main Function
def main():
total, total_quiz = testAvgCalculation()
displayAverage(total, total_quiz)
#Run Main Function
main()
This is hacky as heck, but I tried to work with what was already there. I split the data validation section of the original function off into a separate function. In main() it returns its value counter, which keeps track of how many values were entered, to calculate_average(), which then reads the file line by line until counter becomes 0, which means it's about to read the word "stop" (which allows EOF recognition via the 'and' in the if statement), performs the calculation and returns its values.
def write_file():
#Variables
counter = 0
file = open("Scores.txt", "w")
while True:
#User Input and Variable to stop loop
inpt = input("Enter score: ")
file.write(inpt + "\n")
if inpt.lower()== 'stop':
file.close()
break
counter += 1
return counter
def calculate_average(counter):
total = 0
total_quiz = counter
scores = open("Scores.txt", "r")
s = ""
try:
while counter > 0 and s != 'stop':
s = int(scores.readline())
if int(s) in range(1,101):
total += int(s)
counter -= 1
else:
print("Invalid data in file.")
except ValueError:
print("Invalid data found")
return total, total_quiz
def displayAverage(total, total_quiz):
average = total / total_quiz
print('The Average score is: ', format(average, '.2f'))
print('You have entered', total_quiz, 'scores')
#Main Function
def main():
total, total_quiz = calculate_average(write_file())
displayAverage(total, total_quiz)
#Run Main Function
main()
NOTE: the file is created initially in write mode which overwrites the file each time so you never need a new one. if you want to keep a record you might like to change it to append, though you'll need to manage extracting the proper lines from among old input.
Not pretty at all, but should give you an idea of how to accomplish what you were going for.
In Python, This can not loop many times and cannot find ID number in def.
Every time I try to run the program I get the error
"NameError: name 'askname' is not defined"
and in textfile Keep only the latest data
I expect the output of #def new_booking to be Keep data in files continuously but the actual output is kept data in files just one sentence
I expect the output of #def pre_booked to be Extract data from a file but the actual output is
"NameError: name 'askname' is not defined"
import random
# total=0
# people=0
total1 = 0
total2 = 0
# mini bar
def mini_bar():
mini_bar_total = 0
print("£50 for the Bar")
askbar = input("Would you like a mini bar? Y/N")
if askbar.upper() == "Y":
mini_bar_total = mini_bar_total + 50
return mini_bar_total
# breakfast
def breakfast(people, asknights):
breakfast_total = 0
print("£25 for breakfast")
askdinner = input("Would you like dinner? Y/N")
if askdinner.upper() == "Y":
breakfast_total = (people * 25) * asknights
print("total: £", breakfast_total)
return breakfast_total
# dinner
def dinner(people, asknights):
dinner_total = 0
print("£25 for Dinner")
askdinner = input("Would you like dinner? Y/N")
if askdinner.upper() == "Y":
dinner_total = (people * 25) * asknights
return dinner_total
# number customers
def num_customers():
customer_total = 0
print("£50 an Adult")
askadult = int(input("How many adults? "))
customer_total = askadult * 50
print("total: £", customer_total)
print("£25 a Child")
askchild = int(input("How many children? "))
customer_total = (askchild * 25) + customer_total
print("total: £", customer_total)
return customer_total, askadult, askchild
# number of nights (multiplier)
def num_nights(customer_total):
nights_total = 0
waiting = True
while waiting == True:
try:
asknights = int(input("How many nights are you staying for? "))
nights_total = customer_total * asknights
print("total: £", nights_total)
break
except ValueError:
print("invalid input!")
return nights_total, asknights
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
for i in detailslist:
f = open('newbooking.txt', 'w')
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
# Pre booking ***** is not defind
def pre_booked():
name = input("enter your name or ID number: ")
if name == (askname) or (idnumber):
detailslist = [idnumber, askname, askadult, askchild, asknights, askbar, askbreakfast, askdinner]
for i in detailslist:
print(i)
print("total: £", total)
# main menu, start of program.
def main_menu():
print("##################### WELCOME TO BAY HOTEL ###########################")
print('''Please see what is available at the Hotel,\nAdult Prices per night: £50pp,\nChild price: £25pp,\nMiniBar price: £50 per room,\nBreakfast: £20pp,\nDinner: £25pp''')
while True:
prebook = input("Have you booked? Y/N")
if prebook.upper() == "N":
new_booking()
elif prebook.upper() == "Y":
pre_booked()
main_menu()
- I expect the output of #def new_booking to be Keep data in files continuously but the actual output is keep data in files just one sentence
- I expect the output of #def pre_booked to be Extract data from file but the actual output is "NameError: name 'askname' is not defined"
I think it's because your way to writing data in files.
Working with files has 3 step:
1) Opening file
2) Read [from] / Write [to] file
3) Closing file
third step is what you don't handled it.
You want to write a list in file and you are opening that file in each iteration. It's not a good idea (opening and closing files have their overhead) when you can do it once.
I changed some of your new_booking function and wrote it here:
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
# I handled opening and closing file with [python with statement]
# It close files automatically at the end
with open('newbooking.txt', 'w') as f:
for i in detailslist:
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
The problem here is that you havent actually defined askname in your pre_booked() function so you cant compare against it. In new_booking() you are asking for the username with askname = str(input("Please enter your name? ")) however in the pre_booked() case you dont so you cant use it there without first getting the values from somewhere.
Seeing that you save the new_booking() to a file you probably want to load the data from your file like this:
accounts = []
with open(r"<FILEPATH", "r") as booking_file:
for line in booking_file:
accounts.append(line)
In your new_booking function it might be better to put all the related data in line by line or maybe even use dicts so you can later be sure which values belong together instead of writing all the values into their own line. So you might want to do this instead:
with open('newbooking.txt', 'w') as booking_file:
f.write(detailslist)
Then you can read line by line and possibly use ´eval()´ to get a list or dictionary right from your string or atleast you know the values in one line belong together later on.
You might also want to consider using "a" for append instead of w for write in your bookings file depending if you want to have multiple booking values in your file or just the one.
I am new to programming Python, learning mostly through "learn python the hard way." I recently wrote a script that will help me calculate the overtime earnings for my piece work employees. The script works, but it just doesn't look right to me. I would love input on how I could have saved myself some steps. I know using globals is taboo, but I could not figure out another way to get the answers outside those functions. Thank you!!
# THIS SCRIPT WILL CALCULATE THE NUMBER OF PAID HOURS, OVERTIME HOURS, PIECE RATE HOURS AND OVERTIME HOURS OWED TO AN EMPLOYEE.
number_of_straight_hours_worked = False
number_of_overtime_hours_worked = False
employee_travel_time = False
days_worked = False
employee_earnings = False
employee_hourly_rate = False
employee_overtime_rate = False
#Function to determine number of straight hours worked.
def straight_hours():
global number_of_straight_hours_worked
number_of_straight_hours_worked = float(number_of_straight_hours_worked)
while number_of_straight_hours_worked == False:
number_of_straight_hours_worked = raw_input("How many straight hours did the employee work? ")
try:
int(number_of_straight_hours_worked)
except ValueError:
print("Must use a number")
number_of_straight_hours_worked = False
else:
print ("Thank you.")
#print number_of_straight_hours_worked
# Determines number of overtime hours.
def overtime_hours():
global number_of_overtime_hours_worked
number_of_overtime_hours_worked = float(number_of_overtime_hours_worked)
while number_of_overtime_hours_worked == False:
number_of_overtime_hours_worked = raw_input("How many overtime hours did the employee work? ")
try:
int(number_of_overtime_hours_worked)
except ValueError:
print("Must use a number")
number_of_overtime_hours_worked = False
else:
print ("Thank you.")
#print number_of_overtime_hours_worked
#Calcualtes the employee's overtime rate.
def employee_ot_calculation():
global employee_hourly_rate
global employee_overtime_rate
while employee_hourly_rate == False:
employee_hourly_rate = raw_input("What is the employee's hourly rate? ")
try:
float(employee_hourly_rate)
except ValueError:
print("Must use a number.")
#print employee_hourly_rate
else:
employee_overtime_rate = float(employee_hourly_rate) * 1.5
#Stores travel time hours
def travel_time():
global employee_travel_time
while employee_travel_time == False:
employee_travel_time = raw_input("How many hours of travel? ")
try:
int(employee_travel_time)
except ValueError:
print("Must use a number.")
employee_travel_time = False
else:
print ("Thank you.")
#print employee_travel_time
#Stores number of working days. Not used in version .001
def number_of_days_worked():
global days_worked
while days_worked == False:
days_worked = raw_input("How many days did the employee work? ")
days_worked = float(days_worked)
try:
int(days_worked)
except ValueError:
print("Must use a number.")
days_worked = False
else:
print ("Thank you.")
#Stores earnings made by piece work from employee.
def employee_piece_earnings():
global employee_earnings
while employee_earnings == False:
employee_earnings = raw_input("What did the employee earn through piece rate (format: 0.00)? ")
employee_earnings = float(employee_earnings)
try:
float(employee_earnings)
except ValueError:
print("Must use a number, no dollar sign.")
employee_earnings = False
else:
print ("Thank you.")
#print employee_earnings
# Calculates what the employee will earn this pay period between hours and piece work.
def overtime_piece():
total_hours_worked = float(number_of_straight_hours_worked) + float(number_of_overtime_hours_worked)
# print total_hours_worked
actual_working_hours = float(total_hours_worked) - float(employee_travel_time)
#print actual_working_hours
piece_overtime = float(actual_working_hours) - 40
#print piece_overtime
overtime_rate = float(employee_earnings / actual_working_hours)
#print overtime_rate
earned_straight_pay = float(number_of_straight_hours_worked) * float(employee_hourly_rate)
print "This employee earned $%.2f in straight pay: %.2f hours at $%.2f per hour" % (earned_straight_pay, number_of_straight_hours_worked, employee_hourly_rate)
earned_hourly_overtime = (float(total_hours_worked) - float(actual_working_hours)) * float(employee_overtime_rate)
print "This employee earned $%.2f in hourly overtime: %.2f hours at $%.2f per hour" % (earned_hourly_overtime, number_of_overtime_hours_worked, employee_overtime_rate)
earned_piece_overtime = float(overtime_rate) * float(piece_overtime)
print "This employee earned $%.2f in piece OT: %2f for each of working hour of the %.2f hours of overtime" % (earned_piece_overtime, overtime_rate, piece_overtime)
total_employee_earnings = float(earned_straight_pay) + float(earned_hourly_overtime) + float(earned_piece_overtime) + float(employee_earnings)
print "This employee earned a total of $%.2f this pay period." % total_employee_earnings
employee_ot_calculation()
straight_hours()
overtime_hours()
travel_time()
employee_piece_earnings()
overtime_piece()
To avoid using global variables, what you want to do is use function arguments and return values.
Function arguments
Let's take your first function as an example.
You can define a variable outside of the scope of your function and pass it as an argument between the two parenthesis. You can then manipulate your variable at your convenience inside of your function. You can pass as many arguments as you want.
number_of_straight_hours_worked = 1 # Define a variable outside of function
def straight_hours(number_of_straight_hours_worked): #Pass as argument
number_of_straight_hours_worked += 1 #Do whatever you want
Returning Values
The function straight_hours takes the input on how many straight hours an employee has worked. Instead of using a global variable, what you want to do is to return the value.
number_of_straight_hours_worked = "" # Define a variable outside of function
def straight_hours(number_of_straight_hours_worked): #Pass as argument
number_of_straight_hours_worked = input("How many hours?")
return number_of_straight_hours_worked
#Then retreive the value by doing
number_of_hours = straight_hours(number_of_straight_hours_worked)
As you can see, the line number_of_hours = straight_hours() calls the functions and affects the return the return value to the number_of_hours variable.
Other notes
I would also advise shrinking and simplifying you variable names.
Also, when you declare a variable like you do at the top of your code, I would advise either declare them as NONE or not do it at all. Declaring them to False which is of type boolean to then convert it to a float makes no sense to me.
Separete your validation code from your actual calculations. This way, you can test your calculations separately.
I want to make this program that acts as a bank, how do I make sure the correct ID number must be entered with the correct pin and have it depending on the id you entered print hello then their name and prompt how much money they have in the bank.
attempts = 0
store_id = [1057, 2736, 4659, 5691, 1234, 4321]
store_name = ["Jeremy Clarkson", "Suzanne Perry", "Vicki Butler-Henderson", "Jason Plato"]
store_balance = [172.16, 15.62, 23.91, 62.17, 131.90, 231.58]
store_pin = [1057, 2736, 4659, 5691]
start = int(input("Are you a member of the Northern Frock Bank?\n1. Yes\n2. No\n"))
if start == 1:
idguess = ""
pinguess = ""
while (idguess not in store_id) or (pinguess not in store_pin):
idguess = int(input("ID Number: "))
pinguess = int(input("PIN Number: "))
if (idguess not in store_id) or (pinguess not in store_pin):
print("Invalid Login")
attempts = attempts + 1
if attempts == 3:
print("This ATM has been blocked for too many failed attempts.")
break
elif start == 2:
name = str(input("What is your full name?: "))
pin = str(input("Please choose a 4 digit pin number for your bank account: "))
digits = len(pin)
balance = 100
while digits != 4:
print("That Pin is Invalid")
pin = str(input("Please choose a 4 digit pin number for your bank account: "))
digits = len(pin)
store_name.append(name)
store_pin.append(pin)
I'm very impressed by how much you've elaborated on your program. Here's how I would view your solution.
So to create a login simulation, I would instead use a dictionary. That way you can assign an ID to a PIN. For example:
credentials = {
"403703": "121",
"3900": "333",
"39022": "900"
}
Where your ID is on the left side of the colon and the PIN is on the right. You would also have to assign the ID to a name that belongs to that ID using, you guessed it, a dictionary!
bankIDs = {
"403703": "Anna",
"3900": "Jacob",
"39022": "Kendrick"
}
Now that you've done that, you can create your virtual login system using if/else control flow. I've made my code like this:
attempts = 0
try:
while attempts < 3:
id_num = raw_input("Enter your ID: ")
PIN = raw_input("Password: ")
if (id_num in credentials) and (PIN == credentials[id_num]):
print "login success."
login(id_num)
else:
print "Login fail. try again."
attempts += 1
if attempts == 3:
print "You have reached the maximum amount of tries."
except KeyboardInterrupt:
print "Now closing. Goodbye!"
Note the try and except block is really optional. You could use the break operator like you did in your code if you wanted to, instead. I just like to put a little customization in there (Remember to break out of your program is CTRL-C).
Finally, Python has a way of making life easier for people by using functions. Notice I used one where I put login(id_num). Above this while loop you'll want to define your login so that you can display a greeting message for that particular person. Here's what I did:
def login(loginid):
print "Hello, %s!" % bankIDs[loginid]
Simple use of string formatting. And there you have it. The same can be done with displaying that person's balance. Just make the dictionary for it, then print the code in your login definition.
The rest of the code is good as it is. Just make sure you've indented properly your while-loop inside the elif on the bottom of your code, and your last 2 lines as well.
Hope I helped. Cheers!
So I basically created my functions ( def main(), load(), calc(), and print().
But I do not know how I can allow the user to input the information as many times as he/she wants until they want to stop. Like I they input 5 times, it would also output 5 times. I have tried putting the while loop in the def main() function and the load function but it won't stop when I want it to. Can someone help? Thanks!
def load():
stock_name=input("Enter Stock Name:")
num_share=int(input("Enter Number of shares:"))
purchase=float(input("Enter Purchase Price:"))
selling_price=float(input("Enter selling price:"))
commission=float(input("Enter Commission:"))
return stock_name,num_share,purchase,selling_price,commission
def calc(num_share, purchase, selling_price, commission):
paid_stock = num_share * purchase
commission_purchase = paid_stock * commission
stock_sold = num_share * selling_price
commission_sale = stock_sold * commission
profit = (stock_sold - commission_sale) - ( paid_stock + commission_purchase)
return paid_stock, commission_purchase, stock_sold, commission_sale, profit
def Print(stock_name,paid_stock, commission_purchase, stock_sold, commission_sale, profit):
print("Stock Name:",stock_name)
print("Amount paid for the stock:\t$",format(paid_stock,'10,.2f'))
print("Commission paid on the purchase:$", format(commission_purchase,'10,.2f'))
print("Amount the stock sold for:\t$", format(stock_sold,'10,.2f'))
print("Commission paid on the sale:\t$", format(commission_sale,'10,.2f'))
print("Profit(or loss if negative):\t$", format(profit,'10,.2f'))
def main():
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
main()
You have to give the user some kind of way to declare their wish to stop the input. A very simple way for your code would be to include the whole body of the main() function in a while loop:
response = "y"
while response == "y":
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
response = input("Continue input? (y/n):")
an even simpler way would be two do the following....
while True:
<do body>
answer = input("press enter to quit ")
if not answer: break
alternatively
initialize a variable and avoid the inner if statement
sentinel = True
while sentinel:
<do body>
sentinel = input("Press enter to quit")
if enter is pressed sentinel is set to the empty str, which will evaluate to False ending the while loop.