I'm trying to create a trip planner in python, but after I defined all the functions I'm not able to call and calculate them in the last function tripCost().
In tripCost, I want to put the days and travel destination (city) and the program runs the functions and gives me the exact result of all the 3 functions previously defined.
Code:
def hotelCost():
days = raw_input ("How many nights will you stay at the hotel?")
total = 140 * int(days) print "The total cost is",total,"dollars"
def planeRideCost():
city = raw_input ("Wich city will you travel to\n")
if city == 'Charlotte':
return "The cost is 183$"
elif city == 'Tampa':
return "The cost is 220$"
elif city == 'Pittsburgh':
return "The cost is 222$"
elif city == 'Los Angeles':
return "The cost is 475$"
else:
return "That's not a valid destination"
def rentalCarCost():
rental_days = raw_input ("How many days will you rent the car\n")
discount_3 = 40 * int(rental_days) * 0.2
discount_7 = 40 * int(rental_days) * 0.5
total_rent3 = 40 * int(rental_days) - discount_3
total_rent7 = 40 * int(rental_days) - discount_7
cost_day = 40 * int(rental_days)
if int(rental_days) >= 3:
print "The total cost is", total_rent3, "dollars"
elif int(rental_days) >= 7:
print "The total cost is", total_rent7, "dollars"
else:
print "The total cost is", cost_day, "dollars"
def tripCost():
travel_city = raw_input ("What's our destination\n")
days_travel = raw_input ("\nHow many days will you stay\n")
total_trip_cost = hotelCost(int(day_travel)) + planeRideCost (str(travel_city)) + rentalCost (int(days_travel))
return "The total cost with the trip is", total_trip_cost
tripCost()
Your def rentalCarCost(): is returning nothing..
rentalCost (int(days_travel)) I can't see such function.
Update:
def hotelCost():
days = raw_input ("How many nights will you stay at the hotel?")
total = 140 * int(days) print "The total cost is",total,"dollars"
return total
def planeRideCost():
city = raw_input ("Wich city will you travel to\n")
if city == 'Charlotte':
return 183
elif city == 'Tampa':
return 220
elif city == 'Pittsburgh':
return 222
elif city == 'Los Angeles':
return 475
else:
print "That's not a valid destination"
def rentalCarCost():
rental_days = raw_input ("How many days will you rent the car\n")
discount_3 = 40 * int(rental_days) * 0.2
discount_7 = 40 * int(rental_days) * 0.5
total_rent3 = 40 * int(rental_days) - discount_3
total_rent7 = 40 * int(rental_days) - discount_7
cost_day = 40 * int(rental_days)
if int(rental_days) >= 3:
print "The total cost is", total_rent3, "dollars"
return total_rent3
elif int(rental_days) >= 7:
print "The total cost is", total_rent7, "dollars"
return total_rent7
else:
print "The total cost is", cost_day, "dollars"
return cost_day
def tripCost():
travel_city = raw_input ("What's our destination\n")
days_travel = raw_input ("\nHow many days will you stay\n")
total_trip_cost = hotelCost(int(day_travel)) + planeRideCost () + rentalCarCost(int(days_travel))
return "The total cost with the trip is", total_trip_cost
tripCost()
I suggest you separate user interaction from calculations. I made some changes, and I am pasting it as an example, I am not saying this code does the right thing for your problem, it is just to illustrate that separation. You can also use a cost_table as a dictionary:
cost_table = {
'Charlotte':183,
'Tampa':220,
'Pittsburgh':222,
'Los Angeles':475
}
def hotel_cost(nights):
cost = 140 * int(nights)
return cost
def plane_ride_cost(city):
return cost_table[city]
def rental_car_cost(days):
discount_3 = 40 * days * 0.2
discount_7 = 40 * days * 0.5
total_rent3 = 40 * days - discount_3
total_rent7 = 40 * days - discount_7
cost_day = 40 * days
if days >= 3:
return total_rent3
elif days >= 7:
return total_rent7
else:
return cost_day
def trip_cost(city, nights, car_days):
total = hotel_cost(nights) + plane_ride_cost(city) +\
rental_car_cost(car_days)
return total
city = None
while True:
city = raw_input ("What's our destination?\n")
if city not in cost_table:
print "That's not a valid destination."
else:
break
hotel_nights = raw_input ("\nHow many nights will you stay?\n")
car_days = raw_input ("How many days will you rent the car?\n")
total_trip_cost = hotel_cost(int(hotel_nights)) +\
plane_ride_cost(city) +\
rental_car_cost(int(car_days))
print "The total cost with the trip is", total_trip_cost, "dollars."
Related
I'm working on a program that is a simulation of an order form/receipt. First, the program prints an invoice, then later prints a receipt based on which payment schedule the user selects (1-4 years)
My problem is that I can't find a way to get the invoice and receipt to print the same monthly payment. This is the code used for the invoice:
for NumYears in range (0, 4):
NumYears += 1
NumPayment = NumYears * 12
FinanceFee = 39.99 * NumYears
TotPrice = TotSalesPrice + FinanceFee
MonPay = TotPrice / 12
it prints as:
# Years # Payments Financing Fee Total Price Monthly Payment
----------------------------------------------------------------------
1 12 $39.99 $9,914.99 $826.25
2 24 $79.98 $9,954.98 $829.58
3 36 $119.97 $9,994.97 $832.91
4 48 $159.96 $10,034.96 $836.25
---------------------------------------------------------------------
The second part of the code, for the receipt is:
MonPay1 = TotPrice / 12
MonPay2 = (TotPrice / 12) * 2
MonPay3 = (TotPrice / 12) * 3
MonPay4 = (TotPrice / 12) * 4
while True:
if PayMethod == "1":
print("Terms: 1 Total Payments: 12")
break
elif PayMethod == "2":
print("Terms: 2 Total Payments: 24")
break
elif PayMethod == "3":
print("Terms: 3 Total Payments: 36")
break
elif PayMethod == "4":
print("Terms: 4 Total Payments: 48")
break
while True:
if PayMethod == "1":
print(f"Monthly payment: {MonPay1Dsp:>10s}")
break
elif PayMethod == "2":
print(f"Monthly payment: {MonPay2Dsp:>10s}")
break
elif PayMethod == "3":
print(f"Monthly payment: {MonPay3Dsp:>10s}")
break
elif PayMethod == "4":
print(f"Monthly payment: {MonPay4Dsp:>10s}")
break
else:
break
it prints as:
Sale price: $5,000.00
Trade Allowance: $1,000.00
Price after Trade: $4,000.00
----------
HST: $750.00
License Fee: $75.00
Transfer Fee: $5,050.00
----------
Total Sales Cost: $10,034.96
----------------------------------
Terms: 1 Total Payments: 12
Monthly payment: $836.25
First payment date: 31-Jan-2022
What can I do to fix the discrepancy?
EDIT: Adding in all the calculations. I've gone over them a few times and can't find the error. Maybe I've just been looking at it too long... I don't know.
HST_FEE = .15
TRANS_FEE_LOW = 0.01
TRANS_FEE_HIGH = 0.026
LISC_FEE_LOW = 75.00
LISC_FEE_HIGH = 165.00
PriceAfterTrade = SellPrice - AmtTradeIn
Taxes = HST_FEE * SellPrice
if SellPrice <= 5000.00:
LiscFee = LISC_FEE_LOW
else:
LiscFee = LISC_FEE_HIGH
if SellPrice >= 20000.00:
TransFee = (TRANS_FEE_HIGH * SellPrice) + SellPrice
else:
TransFee = (TRANS_FEE_LOW * SellPrice) + SellPrice
TotSalesPrice = PriceAfterTrade + Taxes + LiscFee + TransFee
The error in your code just hit me: your calculations for MonPay1, ... all used TotPrice, with the value set at the end of the invoice loop, so the value for 4 years!
Here is the code I rewrote (based on my understanding of your different values).
You'll probably have to tweak some things to fit your needs.
# Data
SellPrice = 5000
AmtTradeIn = 1000
HST_FEE = .15
TRANS_FEE_LOW = 0.01
TRANS_FEE_HIGH = 0.026
LISC_FEE_LOW = 75.00
LISC_FEE_HIGH = 165.00
PriceAfterTrade = SellPrice - AmtTradeIn
Taxes = HST_FEE * SellPrice
if SellPrice <= 5000.00:
LiscFee = LISC_FEE_LOW
else:
LiscFee = LISC_FEE_HIGH
if SellPrice >= 20000.00:
TransFee = (TRANS_FEE_HIGH * SellPrice) + SellPrice
else:
TransFee = (TRANS_FEE_LOW * SellPrice) + SellPrice
TotSalesPrice = PriceAfterTrade + Taxes + LiscFee + TransFee
print(TotSalesPrice)
# Code for invoice
MonPay=[0]
for NumYears in range (1, 5):
NumPayment = NumYears * 12
FinanceFee = 39.99 * NumYears
TotPrice = TotSalesPrice + FinanceFee
MonPay.append(TotPrice / 12 / NumYears)
print(MonPay[NumYears])
# Code for receipt
PayMethod = "1" #This is an example for testing purpose
print("Terms: " + PayMethod + " Total Payments: "+str(12*int(PayMethod)))
print(f"Monthly payment: ${MonPay[int(PayMethod)]}")
PFB the below code I am trying to calculate tax. why do I get the NameError: name 'tax' is not defined.
I have defined tax below still it throws the error tax not defined.
hw = float(input("Please enter total hours worked"))
hp = float(input("Please enter the hourly rate"))
# Pay and OT Calculations
rp = hp * hw
if hw == 40 or hw <40 :
ot = 0
tp = rp + ot
elif hw > 40 and hw <50 :
ot = (hw-40)*(hp*1.5)
tp = rp + ot
elif hw > 50 and hw < 60 :
ot = (hw-40)*(hp*2)
tp = rp + ot
elif hw > 60 or hw == 60 :
ot = (hw-40)*(hp*2.5)
tp = rp + ot
else :
print ("Thanks")
# tax Calculations
if tp == 200 :
tax = float((tp/100)*15)
elif tp > 200 and tp < 300 :
tax = ((tp-200)/100*20) + ((200/100)*15)
elif tp >300 and tp < 400 :
tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)
elif tp >400 and tp == 400 :
tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)
else :
print ("Thanks")
# Printing Results
print ("Your Salary has been credited")
print ("Regular Pay = ", rp)
print ("Overtime =", ot)
print ("Gross Salary before tax deductions = ", tp)
print ("Income Tax applicable =", tax)
you are using your variables across the entire function but are only defining them in the if/else cases. This adds a lot of room for error of missing a definition somewhere within a case as in
...
if tp == 200 :
tax = float((tp/100)*15)
elif tp > 200 and tp < 300 :
tax = ((tp-200)/100*20) + ((200/100)*15)
elif tp >300 and tp < 400 :
tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)
elif tp >400 and tp == 400 :
tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)
else :
# NO tax defined here
print ("Thanks")
...
You should define the function-scope variables on the top of your function as:
hw = float(input("Please enter total hours worked"))
hp = float(input("Please enter the hourly rate"))
rp = 0
ot = 0
tp = 0
tax = 0
# Pay and OT Calculations
...
# Printing Results
print ("Your Salary has been credited")
print ("Regular Pay = ", rp)
print ("Overtime =", ot)
print ("Gross Salary before tax deductions = ", tp)
print ("Income Tax applicable =", tax)
By setting these default values you are sure to never miss the variable initialization in your code and you will not need to add extra logic to handle the tax variable in the edge cases where it should not be changed (the else case in your question.
I'm trying to get this program to calculate how much these movies will cost the customer, but the while loop only asks the first three questions it never prints the total, the tax or anything else. Please help me solve this problem!
def checkout():
The_Bourne_Identity = 1
Harry_Potter = 2
Holy_Cross = 3
Arrival = 4
Hidden = 5
price_of_movie = 0
price_of_movie2 = 0
price_of_movie3 = 0
price_of_movie4 = 0
price_of_movie5 = 0
ans = 0
response = 'y'
while response == 'y':
ans = int(input('What movie do you have?'))
q1 = int(input('How many of these do you have'))
response =input('Do you have a different movie?: type y for yes: ')
if ans == The_Bourne_Identity:
price_of_movie = 9.99 * q1
return price_of_movie
elif ans == Harry_Potter:
price_of_movie2 = 15.99 * q1
return price_of_movie2
elif ans == Holy_Cross:
price_of_movie3 = 4.75 * q1
return price_of_movie3
elif ans == Arrival:
price_of_movie4 = 24.99 * q1
return price_of_movie4
elif ans == Hidden:
price_of_movie4 = 29.98 * q1
return price_of_movie5
movie_total_price = price_of_movie + price_of_movie2 + price_of_movie3 + price_of_movie4 + price_of_movie5
movie_tax = movie_total_price * .07
total_cost = movie_tax + movie_total_price
print("Your movies cost,", movie_total_price)
print("Your tax will be,", movie_tax)
print("Your total cost,", total_cost)
def main():
checkout()
main()
when I run it just does the first 3 questions and stops
You are returning midway. The rest codes in the method will not be executed. Instead of return just use movie_total_price for total-cost and add up. Change your method like this (could be refactored a LOT more):
def checkout():
The_Bourne_Identity = 1
Harry_Potter = 2
Holy_Cross = 3
Arrival = 4
Hidden = 5
price_of_movie = 0
price_of_movie2 = 0
price_of_movie3 = 0
price_of_movie4 = 0
price_of_movie5 = 0
movie_total_price = 0
ans = 0
response = 'y'
while response == 'y':
ans = int(input('What movie do you have?'))
q1 = int(input('How many of these do you have'))
response =input('Do you have a different movie?: type y for yes: ')
if ans == The_Bourne_Identity:
movie_total_price += 9.99 * q1
elif ans == Harry_Potter:
movie_total_price += 15.99 * q1
elif ans == Holy_Cross:
movie_total_price += 4.75 * q1
elif ans == Arrival:
movie_total_price += 24.99 * q1
elif ans == Hidden:
movie_total_price += 29.98 * q1
movie_tax = movie_total_price * .07
total_cost = movie_tax + movie_total_price
print("Your movies cost,", movie_total_price)
print("Your tax will be,", movie_tax)
print("Your total cost,", total_cost)
You return from the checkout function if any of the conditions is True. If there isn't a reason to do so, comment out the return statements and you should see the remaining logs.
I dont understand why the code doesnt work and they have repeated the questions to me 4 times. and say that float is not callable. i have tried doing this for quite awhile but i dont seem to get anything at all. is there any easier way for python3? I just learnt this language 2 weeks ago. its not a whole new world to me but many of the things i am not familiar with. such as indentation
def get_taxi_info():
flag_down = float(input("What's the flag-down fare: $"))
within = float(input("What's the rate per 400 meters within 9.8km? $"))
beyond = float(input("What's the rate per 350 meters beyond 9.8km? $"))
distance = float(input("What's the distance traveled (in meters)? "))
peak = input("Is the ride during a peak period? [yes/no]")
mid6 = input("Is the ride between midnight and 6am? [yes/no]")
location = input("Is there any location surcharge? [yes/no]")
surloca = float(input("What's the amount of location surcharge?"))
return (flag_down, within, beyond, distance, peak == 'yes', mid6 == 'yes', location == 'yes', surloca)
def calculate_taxi_fare():
dist = get_taxi_info()
if dist[3] > 9800:
extra = (dist[3] - 9800) % 350
if extra == 0:
a = (extra//350) + 22
else:
a = (extra//350) + 23
return a
elif dist[3] <= 9800:
extra = (dist[3] - 1000) % 400
if extra == 0:
a = (extra//400)
else:
a = (extra//400) + 1
return a
def peakornot():
peak = get_taxi_info()
if peak[4] == True and peak[5] == False:
surcharge = 1.25
return surcharge
elif peak[4] == False and peak[5] == True:
surcharge = 1.50
return surcharge
taxifare = calculate_taxi_fare()
info = get_taxi_info()
peak1 = peakornot()
taxifare = calculate_taxi_fare()
if info[6] == True:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
elif info[6] == False:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
The function calculate_taxi_fare returns a float, so on this line taxifare is a float
taxifare = calculate_taxi_fare()
Therefore you cannot say taxifare() because it looks like a function call, so you can just use for example
info[1] * taxifare
I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:
I keep getting this error and I don't know what is wrong, please help :) thanks!
Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 43000:
^
SyntaxError: invalid syntax
CODE:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax
Steps to correct your code
step1 : the salary data type should be of int, to correct..use the following code
step 2: Indentation is compulsory in python, so indent your code very well
step 3: Add an else statement after the conditional statements
step 4: indent return statement
change your code to this one
salary = int(raw_input ("What is your salary?"))
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
else :
tax = undefined
return tax
It felt like there was a better way of doing this, so I came up with an alternative route:
tax_bands = [11000, 43000, 150000]
tax_amts = [0.2, 0.4, 0.45]
salary = 43001
Placing the thresholds and amounts into a list means that you can change them more easily if you need to.
The function below creates a list of the tax calculations, tax_list, and then a separate list of the maximum tax liability in each band called max_tax (the upper band has no maximum).
It then compares the values in the lists, and overwrites the tax_list if the corresponding value is larger than the maximum.
Then it calculates the sum of all values in tax_list greater than zero and returns it.
def taxes(salary, tax_bands, tax_amts):
tax_list = [(pct * (salary - band)) for (band, pct) in zip(tax_bands, tax_amts)]
max_tax = []
for index, sal in enumerate(tax_bands[:-1]):
max_tax.append(tax_bands[index + 1] - sal)
max_tax = [segment * tax for segment, tax in zip(max_tax, tax_amts[:-1])]
for index, value in enumerate(tax_list):
try:
if value > max_tax[index]:
tax_list[index] = max_tax[index]
except:
pass
tax_to_pay = sum([x for x in tax_list if x > 0])
return tax_to_pay
print taxes(salary, tax_bands, tax_amts)
salary = input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nYour net annual salary is: {} GBP".format(salary - taxes(salary, tax_bands, tax_amts))
To be super safe, you could also have the first line in the function call int(salary) using a try except just to check that it's the right type and that someone hasn't entered 43,000.
That because there are indent error in line number 12, now you can just copy pust this :
note : salary > 11000 and salary < 43000 equivalent to 11000 < salary < 43000 in python:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
while true:
if salary < 11000:
tax = 0
elif 11000 < salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax
As the comments have already stated, your indentation is incorrect. See below:
def taxes(salary):
salary >= 0
tax = 0
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
print("Value of tax is: " + str(tax))
return tax
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
print("\nHere is your net salary after taxes: %r" % (taxes(int(salary))))
With python, indentations are how you tell the interpreter which blocks of code fall where (unlike with Java for example with semicolons being the end of line delimiter). By not indenting properly on your elif statements, you are essentially telling the program there is an elif without an if hence your syntax problem.