Python - Not printing output in a function - python

I am new to Python and I am trying to write a code that takes from the user an input of money spent, number of transactions and it gives back the average value that was spent. So far I have this:
def compra(conta, valor):
conta["saldo"] = conta["saldo"] + valor
conta["transacoes"] = conta["transacoes"] + 1
conta["media"] = (conta["media"]*(conta["transacoes"]-1)+valor)/conta["transacoes"]
return(conta)
print(f"Os valores de saldo, transações e média são: {conta['saldo']} {conta['transacoes']} {conta['media']}")
while True:
valordacompra = float(input('Digite o valor da compra: '))
But I am not sure how to make it show on the screen what the values are after getting the input. If some more information is needed let me know ! Thank you

import math
money_spent = int(input('How much money was spent?: '))
num_transactions = int(input('How many transactions?: '))
average_value = money_spent / num_transactions
print("The average value is " + str(average_value) + '$')
Also keep an eye on exceptions. For example if the user typed in "cat" instead of a number. You can do this by using try ... except
import math
while True:
try:
money_spent = int(input('How much money was spent?: '))
num_transactions = int(input('How many transactions?: '))
average_value = money_spent / num_transactions
print("The average value is " + str(average_value) + '$')
break
except:
ValueError
print('Type in a number')

Related

Python - Is there a way to ask the same series of questions and store the each set of answers until the user is done?

As a very new Python writer, I'm making a calculator that's supposed to ask the user a series of questions, and then determine an approximate total amount of money they've spent on chapstick throughout their life. I'm currently trying to loop a series of questions so that the answers can be used to calculate a total.
while brand != ''
brand = str(input('Enter a brand of chapstick you use: '))
brand = brand.title()
brand_cost = float(input('How much does', brand, 'chapstick cost? $'))
brand_quantity = int(input('How many', brand, 'chapstick(s) do you own? '))
brand_regularly = int(input('How many', brand, 'chapsticks do you finish per year? '))
brand_since = int(input('At what age did you first buy', brand, 'Chapstick? '))
You can append all the values to a list so that you can calculate them at the end when the use is done inputting his/her values. The code for this is shown below:
prices = []
quantity = []
per_year = []
since = []
while True:
brand = str(input('Enter a brand of chapstick you use: '))
brand = brand.title()
brand_cost = float(input('How much does ' + brand + ' chapstick cost? $'))
brand_quantity = int(input('How many ' + brand + ' chapstick(s) do you own?'))
brand_regularly = int(input('How many' + brand + ' chapsticks do you finish per year? '))
brand_since = int(input('At what age did you first buy' + brand + 'Chapstick? '))
prices.append(brand_cost)
quantity.append(brand_quantity)
per_year.append(brand_regularly)
since.append(brand_since)
is_complete = str(input('Is that all (y/n)'))
if is_complete == 'y':
break
elif is_complete == 'n'
continue
After the user is done, you will have 4 lists containing all of the inputed values which you can use to do do your calculations.

Writing to a file in a for loop and def is not defined

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.

Need help simplifying my script in Python

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.

making a piggy bank program in python

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.

How can you make the user change the content of a variable in Python 3.2

i am just writing a simple currency converter program, and the one problem that i am facing is that i can't think how to have the user change the content of the variable. Below is an the basic bit:
def D2Y():
def No():
newconv=float(input("What is the rate that you want to use: "))
amount=float(input("How much do you want to convert: $"))
conversionn=round(amount*newconv,2)
print("¥",conversionn)
return (rerun())
def Yes():
conrate2=float(97.7677)
amount=float(input("How much do you want to convert: $"))
conversion=round(amount*conrate2,2)
print("¥",conversion)
return (rerun())
def rerun():
rerun=int(input("Do you want to go again?\n1 - Yes\n2 - No\nChoice: "))
if rerun==1:
return (main())
else:
print("Thank you for converting")
conrate1=int(input("The currency conversion rate for Yen to 1 US Dollar is ¥97.7677 to $1\n1 - Yes\n2 - No\nDo you want to use this rate?: "))
if conrate1==1:
return (Yes())
else:
return (No())
I dont know how you do it. I dont mind if you get rid of the def functions.
Here's an approach that does away with the functions and allows you to modify the exchange rate:
rate = CONVERSION_RATE = 97.7677
while True:
print "The currency conversion rate for Yen to 1 US Dollar is ¥%.4f to $1" % rate
print 'Select an option:\n1)Modify Conversion Rate\n2)Convert a value to dollars\n0)Exit\n'
choice = int(raw_input('Choice: '))
if choice == 0:
print("Thank you for converting")
break
if choice == 1:
try:
rate = float(raw_input("What is the rate that you want to use: "))
except ValueError:
rate = CONVERSION_RATE
amount = float(raw_input("How much do you want to convert: $"))
print "¥", round(amount * rate,2)
print '\n\n'
In use, it looks like this:
The currency conversion rate for Yen to 1 US Dollar is ¥97.7677 to $1
Select an option:
1)Modify Conversion Rate
2)Convert a value to dollars
0)Exit
Choice: 2
How much do you want to convert: $1.00
¥ 97.77
...
Choice: 1
What is the rate that you want to use: 96.9000
How much do you want to convert: $1.00
¥ 96.9

Categories