I have some code written for a school project but it shows errors on all of the cost parts of my code
fullname = input("whats your name?")
print("hello",fullname,)
print("room 1")
width=input("how wide is the room?")
length=input("how long is the room?")
area = float(length)*float(width)
print("the total area is",area,)
q = input("do you want another room?")
if q == "yes":
print("room 2 ")
widtha=input("how wide is the room?")
lengtha=input("how long is the room?")
areaa = float(lengtha) * float(widtha)
print("the total area is",areaa,".")
else:
flooring=input("do you want to have wood flooring(10) or tiled flooring(15)")
if flooring == "wood":
costaa = float(area)+ float(areaa)*10
print("total cost is ",costaa,)
if flooring == "tiled":
costab = float(area)+ float(areaa)*15
print("total cost is £",costab,)
It will show NameError:costab or NameError:costaa as not defined depending which I select.
The answer to your problem is simple.
When the computer says: Do you want another room? and you say no, you are not defining the value of areaa at all. Therefore, the areaa does not exist because you didn't specify it. I've made some changed to your code to make it working, hope it help!
fullname = input("Whats Your Name?")
print("Hello", fullname)
print("\nRoom 1")
width = input("How wide is the room?")
length = input("How long is the room?")
area = float(length) * float(width)
print("The Total Area is", area)
q = input("\nDo you want Another Room? (y/n)")
if q == "y":
print("\nRoom 2")
width2 = input("How wide is the room?")
length2 = input("How long is the room?")
area2 = float(length2) * float(width2)
print("The Total Area is", area2,".")
flooring=input("\nDo you want to have Wood Flooring(10) or Tiled Flooring(15)? (wood/tiled)")
if flooring == 'wood':
cost = area + area2 * 10
print("Total Cost is ",cost)
if flooring == 'tiled':
cost2 = area + area2 * 15
print("Total Cost is ",cost2)
else:
flooring=input("\nDo you want to have Wood Flooring(10) or Tiled Flooring(15)? (wood/tiled)")
if flooring == 'wood':
cost = area * 10
print("Total Cost is ",cost)
if flooring == 'tiled':
cost2 = area * 15
print("Total Cost is ",cost2)
I have tested your code and runs ok on my pc. Maybe it's your configurations.
For python 2
input_variable = raw_input("Enter your name: ")
If you are using Python 3.x, raw_input has been renamed to input
Related
I have been experimenting with creating an investment calculator, and I want to print the annual totals as well as the annual compounded interest. It's doing the annual totals fine, but not the annual interest. My inputs are $10000.00 principle, at 5% interest over 5 years.
start_over = 'true'
while start_over == 'true':
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate"))
addition = int(input("Type annual Addition"))
time = int(input("Enter number of years to invest"))
real_rate = rate * 0.01
i = 1
print('total', principle * (1 + real_rate))
while i < time:
principle = (principle + addition) * (1 + real_rate)
i = i + 1
print('total', principle)
for i in range(time):
amount = i * (((1 + rate/100.0) ** time)) * principle
ci = amount - principle
i += 1
print("interest = ",ci)
redo_program = input('To restart type y or to quit type any key ')
if redo_program == 'y':
start_over = 'true'
else:
start_over = 'null'
Here are my outputs:
Type the amount you are investing: 10000
Type interest rate5
Type annual Addition0
Enter number of years to invest5
total 10500.0
total 10500.0
total 11025.0
total 11576.25
total 12155.0625
interest = -12155.0625
interest = 3358.21965978516
interest = 18871.50181957032
interest = 34384.78397935548
interest = 49898.06613914064
To restart type y or to quit type any key
Give this a go:
# Calculate year's values based on inputs and the current value of the account
def calc(current, addition, rate, year):
multiplier = 1 + rate/100 # The interest multiplier
new_total = (current + addition) * multiplier # Calculate the total
interest = round((new_total - current - addition), 2) # Interest to nearest penny/cent
return new_total, interest
def main():
# Inputs
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate: "))
addition = int(input("Type annual Addition: "))
invst_time = int(input("Enter number of years to invest: "))
# Sets current account value to principle
current = principle
# Prints values for each year of investment
for i in range(invst_time):
total, interest_gained = calc(current, addition, rate, i+1)
print("At the end of Year: ", i+1)
print("Total: ", total)
print("Interest: ", interest_gained)
print("------")
current = total # Updates value of account
# Restart Program check
while 1:
repeat_choice = input("Would you like to restart and check with different values? (Y/N)")
if repeat_choice == "Y":
main()
elif repeat_choice == "N":
print("Thanks for using the calculator")
break
else:
print("Enter Y or N!") # Error handler
continue
main()
I right now have them set as global but I do not know how to set up the argument and parameters in order to save the variable bmr in order to use it in another function such as get_calorie_requirement. I know i have a lot of inputs in order to get the bmr. Should I define the formula get_bmr? I am stuck on something simple because I am trying to do bmr= get_bmr(bmr) but that is wrong.
import math
def get_bmr():
gender = input("What is your gender: M or F?")
age = int(input("What is your age?"))
height = int(input("What is your height in inches?"))
weight = (int(input("What is your weight in pounds?")))
bmr_wght_constant = 4.536
bmr_hght_constant = 15.88
bmr_age_constant = 5
if gender == 'M':
bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) + 5)
elif gender == 'F':
bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) - 161)
else:
print("Please try again.")
return bmr
def get_daily_calorie_requirement():
dcr_1 = 1.2
dcr_2 = 1.375
dcr_3 = 1.55
dcr_4 = 1.725
dcr_5 = 1.9
act_lvl = int(input("What is your activity level?"))
if act_lvl == 1:
daily_calorie_requirement = int(bmr * dcr_1)
elif act_lvl == 2:
daily_calorie_requirement = int(bmr * dcr_2)
elif act_lvl == 3:
daily_calorie_requirement = int(bmr * dcr_3)
elif act_lvl == 4:
daily_calorie_requirement = int(bmr * dcr_4)
elif act_lvl == 5:
daily_calorie_requirement = int(bmr * dcr_5)
else:
print("Please choose a number 1-5.")
return daily_calorie_requirement
def main():
print("Hello, welcome to my intergration project!")
print("The purpose of this program is to help the user reach their goal and provide helpful suggestions.")
print("It will do this by taking your age, gender, height and your level of physical activity in order to calculate your Basal Metabolic Rate(BMR)")
print("Your BMR is how many calories you burn in a single day. Combining your BMR with your goals we can suggest a meal plan and excercises that will help reach your goals")
print("Let's get started! I will start by asking you a few questions in order to make a profile and give you the best informed advice.")
if gender == 'M':
bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) + 5)
elif gender == 'F':
bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) - 161)
else:
print("Please try again.")
print("Your BMR is: ", bmr)
print("Great! Now that we have calculated your Basal Metabolic Rate, let's calculate your daily calorie requirement!")
print("This is the calories you should be taking in to maintain your current weight")
print("How active are you on a scale of 1-5?")
print("1 being you are sedentary (little to no exercise)")
print("2 being lightly active (light exercise or sports 1-3 days a week)")
print("3 being moderately active (moderate exercise 3-5 days a week)")
print("4 being very active (hard exercise 6-7 days a week)")
print("5 being super active (very hard exercise and a physical job)")
print("Exercise would be 15 to 30 minutes of having an elevated heart rate.")
print("Hard exercise would be 2 plus hours of elevated heart rate.")
daily_calorie_requirement = get_daily_calorie_requirement()
It would be more helpful to show us the error you're facing, it's hard to tell what the issue could be since the code isn't working either. If you have a traceback, that would be useful in solving this Question.
Assigning simply occurs when there is a variable on the left hand side of an =. When calling a method such as get_bmr() what ever is return'ed by this function will be assigned.
Your code could be failing since you're trying to get gender but this isn't defined in under function main. You can replace the if gender "M" elif "F" with simply the following. (Since you call all this in get_bmr)
bmr = get_bmr()
If you're wanting to pass bmr into the next function would creating an argument for get_daily_calorie_requirement resolve the issue?
def get_daily_calorie_requirement(bmr):
dcr_5 = 1.9
return int(bmr * dcr_5)
def main():
bmr = get_bmr()
daily_calorie_requirement = get_daily_calorie_requirement(bmr)
if __name__ == '__main__':
main()
If you want to simplify it you could move some of the parameters into arguments:
def get_bmr(gender, age, height, weight):
""" Calculate BMR using the following formula:
bmr = weight_const*weight ... etc.
"""
gender_coef = 5 if gender == "M" else -161
return int((4.536 * weight) + (15.88 * height) - (5 * age) + 5)
gender = input("What is your gender: M or F?")
while gender not in ["M", "F"]:
print("Please try again, accepted values: M/F")
gender = input("What is your gender: M or F?")
age = int(input("What is your age?"))
height = int(input("What is your height in inches?"))
weight = int(input("What is your weight in pounds?"))
bmr = get_bmr(gender, age, height, weight)
Few things that can be tricky, naming variables the same as your functions, or simply forgetting to return in a function.
I have 3 more cars that I have but I need to know how to loop things like the car input so it will allow you to input it again if you do the wrong input same thing with the extras so they have to be either 1 or 0.
print("===================================================")
print("==============Car Finance Calculations=============")
print(" Choose your veicle: ")
print(" SUV type 1 ")
print(" Hatch type 2 ")
print(" Sedan type 3 ")
print("===================================================")
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
if caaaaaaaar == 1:
carsvalue = int(input("Please enter you cars value: "))
residual = carsvalue * 0.30
financing = carsvalue - residual
print(" financing value for the car is: ", round(financing,2))
print(" Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r*((r+1)**n))/(((r+1)**n)-1))
print(" Your Montly financing rate is: ", round(Financingcost,2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
print(" If you would like fuel type 1 if not type 0")
print(" If you would like insurance type 1 if not type 0")
print(" if you would like Maintenance type 1 if not type 0")
print("======================================================")
if caaaaaaaar == 1:
x, y, z = [int(x) for x in input("Enter Your extras with spaces:").split()]
print("=======================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost,2))
if x == 0:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost,2))
if y ==0:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ",insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost,2))
if z == 0:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ",maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras,2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING,2))
You want to use a while loop.
Like this:
carsEntered = 0
while (carsEntered <= 4):
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
carsEntered += 1
You could also use a for loop instead but that depends on what you want to do.
As per my understanding of the question you want to run an iteration until the user gives the right answer.
In that case, you can use flag variable in while.
flag = False
while(flag is False):
if(condition_statisfied):
flag = True
I suggest that you put your vehicle types in a dictionary:
vehicle_type_dict = {
1: "SUV type",
2: "Hatch type",
3: "Sedan type"
}
and do a while-loop to check if your input is in the dictionary:
while True:
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
if caaaaaaaar not in vehicle_type_dict:
continue #loop again if input not in the dictionary
#read next line of code if input is in the dictionary
#do something below if input is correct
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
break #end loop
My recommendation is to take a functional approach to this problem. You are calling int(input()) multiple times and want to validate the user input before proceeding on to the next lines each time. You can do this in a function that will continue to loop until the input is confirmed as valid. Once the input is validated, you can exit the function's frame by returning the value using the return key word.
# This is the function definition.
# The code in this function does not execute until the function is called.
def prompt_int(
text,
minimum=0,
maximum=1,
error="The value you entered is not valid try again."
):
# when the function is called it will start a second while loop that will keep looping
# until valid input is entered
while True:
try:
val = int(input(text))
if minimum <= val <= maximum:
return val
raise ValueError
except ValueError:
print(error)
# This is the outer while loop. It will keep looping forever if the user so chooses.
while True:
# instead of calling print() a bunch one option is to assign a docstring to a variable
car_prompt = '''
===================================================
==============Car Finance Calculations=============
Choose your veicle:
SUV: 1
Hatch: 2
Sedan: 3
===================================================
Please enter the number for the car you want to finance or 0 to exit:\n
'''
# This is where we first call the function.
# Our docstring will be passed into the function to be used as a prompt.
# We also pass in some args for maximum and minimum params
caaaaaaaar = prompt_int(car_prompt, 0, 3)
# 0 is false so we can exit the while loop if the user enters 0
if not caaaaaaaar:
break
year_prompt = "Enter years of the car loan (3, 4 or 5):\n"
years = prompt_int(year_prompt, 3, 5)
if caaaaaaaar == 1:
val_prompt = "Please enter you cars value:\n"
carsvalue = prompt_int(val_prompt, 0, 2147483647)
residual = carsvalue * 0.30
financing = carsvalue - residual
print("Financing value for the car is: ", round(financing, 2))
print("Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r * ((r + 1) ** n)) / (((r + 1) ** n) - 1))
print(" Your Montly financing rate is: ", round(Financingcost, 2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
x = prompt_int("If you would like fuel type 1 else type 0:\n")
y = prompt_int("If you would like insurance type 1 else type 0:\n")
z = prompt_int("If you would like Maintenance type 1 else type 0:\n")
print("======================================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost, 2))
else:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost, 2))
else:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ", insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost, 2))
else:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ", maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras, 2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING, 2))
elif caaaaaaaar == 2:
# Put your code for car 2 in this block.
# If it is like car 1 code except the value of a few variables
# then make another func
pass
else:
# Car 3 code...
pass
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 have a quick question for you all. I'm currently working on an sample Airline reservation system and I'm having difficulties displaying the total amount discounted if the user is a frequent flyer (10% discount rate). Below is my code:
user_people = int(raw_input("Welcome to Ramirez Airlines! How many people will be flying?"))
user_seating = str(raw_input("Perfect! Now what type of seating would your party prefer?"))
user_luggage = int(raw_input("Thanks. Now for your luggage, how many bags would you like to check in?"))
user_frequent = str(raw_input("Got it. Is anyone in your party a frequent flyer with us?"))
user_continue = str(raw_input("Your reservation was submitted successfully. Would you like to do another?"))
luggage_total = user_luggage * 50
import time
print time.strftime("Date and time confirmation: %Y-%m-%d %H:%M:%S")
seats_total = 0
if user_seating == 'economy':
seats_total = user_people * 916
print ('The total amount for your seats is: $'),seats_total
elif user_seating == 'business':
seats_total = user_people * 2650
print ('The total amount for your seats is: $'),seats_total
else:
print ('The total amount for your seats is: $'),user_people * 5180
print ('The total amount of your luggage is: $'),luggage_total
print ('Your subtotal for your seats and luggage is $'), luggage_total + seats_total
discount_amount = 0
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
after_discount = before_discount * discount_rate
discount_amount = before_discount - after_discount
print discount_amount
else:
print ('Sorry, the discount only applies to frequent flyers!')
While I'm not receiving an error, my output is incorrect. This is what is being displayed:
Discount amount of 1738.8
This obviously is incorrect as that is the price after the discount. I'm trying to display the total DISCOUNT as well as the price AFTER the discount has been applied.
Any help would be appreciated! Thanks!
You have more than one bug. First, in the else of the first if, you don't compute seat_total, so following computations will crash -- you just do
print ('The total amount for your seats is: $'),user_people * 5180
rather than the obviously needed
seat_total = user_people * 5180
print ('The total amount for your seats is: $'), seat_total
(the parentheses are useless but they don't hurt so I'm letting them be:-).
Second, look at your logic for discounts:
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
after_discount = before_discount * discount_rate
discount_amount = before_discount - after_discount
You're saying very explicitly that with a discount the user pays 1/10th of the list price -- then you complain about it in your Q!-)
It is, again, obvious (to humans reading between the lines -- never of course to computers:-), that in sharp contrast to what you say, what you actually mean is:
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
discount_amount = before_discount * discount_rate
after_discount = before_discount - discount_amount