My program is supposed to display the total occupancy rate and individual floor occupancy of a hotel. The total amount of rooms occupied does not accumulate with each iteration. I've attempted to dissect the issue but to no avail. I have a feeling the problem is obvious.
#Welcome message and hotel info
print("WELCOME TO THE GRAND NEW HOTEL!!!")
print("-----------------------------------")
print("Total number of floors in the hotel : 8")
print("Total number of rooms in each floor : 30")
print("Total Number of rooms in the hotel :240\n")
print("-----------------------------------\n")
#Variable for Hotel
total_in_floor = 30
total_in_hotel = 240
rented_in_floor = 0
rented_in_hotel = 0
rate_of_floor = 0
rate_of_hotel = 0
#User Input
for i in range(8):
while True:
try:
#loop until the nimber is correct
print("Please enter rented rooms in Floor No. {0}".format(i+1))
rented_in_floor = int(input())
if 0 <= rented_in_floor <= 30:
break
except ValueError:
#int() will not go past until input is a valid number
print("Retry")
rate_of_floor = int((rented_in_floor))/int((total_in_floor))*100
print("Occupancy rate of Floor No.{0} is = {1}%\n".format(i+1,round(rate_of_floor,2)))
rented_in_hotel = int(rented_in_hotel) + int(rented_in_floor)
rate_of_hotel = int((rented_in_hotel))/int((total_in_hotel))*100
print("Total rooms rented in entire hotel : {0}\n".format(rented_in_hotel))
print("Occupancy rate of the hotel is = {0} % \n".format(round(rate_of_hotel,2))
#Welcome message and hotel info
print("WELCOME TO THE GRAND NEW HOTEL!!!")
print("-----------------------------------")
print("Total number of floors in the hotel : 8")
print("Total number of rooms in each floor : 30")
print("Total Number of rooms in the hotel :240\n")
print("-----------------------------------\n")
#Variable for Hotel
total_in_floor = 30
total_in_hotel = 240
rented_in_floor = 0
rented_in_hotel = 0
rate_of_floor = 0
rate_of_hotel = 0
#User Input
for i in range(8):
while True:
try:
#loop until the nimber is correct
print("Please enter rented rooms in Floor No. {}".format(i+1))
rented_in_floor = int(input())
if 0 <= rented_in_floor <= 30:
rate_of_floor = int((rented_in_floor)) / int((total_in_floor)) * 100
print("Occupancy rate of Floor No.{0} is = {1}%\n".format(i + 1, round(rate_of_floor, 2)))
break
except ValueError:
#int() will not go past until input is a valid number
print("Retry")
rented_in_hotel = int(rented_in_hotel) + int(rented_in_floor)
rate_of_hotel = int((rented_in_hotel))/int((total_in_hotel))*100
print("Total rooms rented in entire hotel : {0}\n".format(rented_in_hotel))
print("Occupancy rate of the hotel is = {0} % \n".format(round(rate_of_hotel,2)))
Try this code.
Hope this helps.
If I understood correctly what you need, I think this modified code may help you.
I have added some comments in the parts I've modified or added.
print("WELCOME TO THE GRAND NEW HOTEL!!!")
print("-----------------------------------")
print("Total number of floors in the hotel : 8")
print("Total number of rooms in each floor : 30")
print("Total Number of rooms in the hotel :240\n")
print("-----------------------------------\n")
total_in_floor = 30
total_in_hotel = 240
rented_in_floor = 0
rented_in_hotel = 0
# rate_of_floor = 0 #not necessary at this point
rate_of_hotel = 0
list_of_floors = [] # create a list where storing "rented_in_floor" for each floor
for i in range(8):
while True:
try:
print("Please enter rented rooms in Floor No. {0}".format(i+1))
rented_in_floor = int(input())
if 0 <= rented_in_floor <= 30:
list_of_floors.append(rented_in_floor) # add the number of rented rooms in the "i+1"th floor to the list
rented_in_hotel += rented_in_floor # accumulate the total amount of rooms occupied in the hotel
break
else: # in the case the input number is larger than 30, explain what is the problem
print("Please enter a number of rented room not larger than 30")
except ValueError:
print("Retry")
for i in range(8): # print all the floors' occupancy rates
rented_in_floor_temp = list_of_floors[i] # select the number of rented room in the floor of index i inside "list_of_floors" (basically, the "i+1"th floor of the hotel)
rate_of_floor = int((rented_in_floor_temp))/int((total_in_floor))*100 # same as before, but with "rented_in_floor_temp"
print("Occupancy rate of Floor No.{0} is = {1}%\n".format(i+1,round(rate_of_floor,2)))
# rented_in_hotel = int(rented_in_hotel) + int(rented_in_floor) # delete, "rented_in_hotel" has been defined above already
rate_of_hotel = int((rented_in_hotel))/int((total_in_hotel))*100
print("Total rooms rented in entire hotel : {0}\n".format(rented_in_hotel))
print("Occupancy rate of the hotel is = {0} % \n".format(round(rate_of_hotel,2)))
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 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
The issue i am having is getting the value of a returned item to update from different functions within a main function.
I have tried syntax to see if that changed anything, but I am not sure what needs to happen to get (in this case: the count and total).
I have also tried setting the functions = count, total but that returned an error.
def main():
terminate = False
print("Welcome to the self-checkout system at Wake-Mart.")
count, total = scan_prices()
print('')
disc = discount(count, total)
print('')
promo = promotion(count, total)
balance = total
def scan_prices():
total = 0
count = 0
prices = float(input("Enter the price of the first item:"))
while prices > 0:
count +=1
total = total + prices
print("Number of items:", count, "Total:", total)
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
while prices < 0:
print("Price cannot be negative.")
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
if prices > 0:
count +=1
total = total + prices
print("Number of items:", count, "Total:", total)
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
continue
return count, total
def discount(count, total):
if count >= 10:
print("You've got a 10% discount for buying 10 items or more.")
total = total * .9
print("Number of items:", count, "Total:", total)
return total
def promotion(count, total):
if total >= 50:
card = input(print("Do you want to buy a $50 gift card for $40 [y/n]:"))
if card == 'Y' or 'y':
print("Thank you for buying a giftcard.")
count +=1
total = (total * .9) + 40
print("Number if items:", count, "Total:", total)
else:
print("Thank for your purchases.")
print("Number if items:", count, "Total:", (total * .9))
return count, total
main()
I am just wanting the total and count to be updated as I move from one function execution to the next within the main function.
It looks like your main should take the return of one function and pass it to the next:
def main():
terminate = False
print("Welcome to the self-checkout system at Wake-Mart.")
count, total = scan_prices()
print('')
total = discount(count, total)
print('')
count, total = promotion(count, total)
balance = total
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
So here is my code ive tried so many loop options and just cant seem to get it to loop the whole thing when any help would be apreciated
# Displays the Program Header
print('----------------------------------------------------------------------')
print('The Innovation University of Australia (IUA) Grade System')
print('----------------------------------------------------------------------')
# These print commands display the spaces to divide the sections
print()
# Asks the lecturer to input all marks out of 100
print('Please enter all marks out of 100.')
#Asks to input stydents ID and name
#Asks the to input the marks for Assignment 1 and Assignment 2
# and the Final Exam and stores them as floats
studentID = input('Please enter the student ID: ')
studentname = input('Please enter the student name: ')
assignment1 = float(input('Please enter the marks for Assignment 1: '))
assignment2 = float(input('Please enter the marks for Assignment 2: '))
final_exam = float(input('Please enter the marks for the Final Exam: '))
print()
# Displays the Thank You! message
print('Thank You!')
print()
# Calculates the weighted mark for Assignment 1, Assignment 2, and the
# total weighted mark of the Assignments by mutiplying by 20% and 30%
weighted_assignment1 = 0.2 * assignment1
weighted_assignment2 = 0.3 * assignment2
total_weighted_assignments = weighted_assignment1 + weighted_assignment2
# Displays the weighted mark for Assignment 1, Assignment 2, and the total
# weighted mark of the Assignments
print('Weighted mark for Assignment 1:', int(weighted_assignment1))
print('Weighted mark for Assignment 2:', int(weighted_assignment2))
print('Total weighted mark of the assignements:', int(total_weighted_assignments))
print()
# Calculates the weighted mark for the Final Exam and the total weighted
# mark for the subject
weighted_final_exam = 0.5 * final_exam
total_weighted_subject = total_weighted_assignments + weighted_final_exam
# Displays the weighted mark of the Final Exam and the total weighted mark
# for the subject
print('Weighted mark for Final Exam is:', int(weighted_final_exam))
weightedtotal = print('Total weighted mark for the subject:', int(total_weighted_subject))
print()
# Calculates the bonus mark for the subject depending on how high the
# total mark is
if total_weighted_subject > 50 and total_weighted_subject <= 70:
bonus_mark = (total_weighted_subject - 50) * 0.1
elif total_weighted_subject > 70 and total_weighted_subject <= 90:
bonus_mark = (total_weighted_subject - 70) * 0.15 + 2
elif total_weighted_subject > 90 and total_weighted_subject <= 100:
bonus_mark = (total_weighted_subject - 90) * 0.20 + 5
else:
bonus_mark = 0
# Displays the bonus mark for the subject
print('Bonus mark:', format(bonus_mark, '.1f'))
# Calculates the total mark for the subject with the bonus mark
total_with_bonus = total_weighted_subject + bonus_mark
# Check if total mark with bonus is greater than maximum
# possible mark of 100 and if it is set to 100 and display
# total mark with bonus
if total_with_bonus > 100:
total_with_bonus = 100
print('Total mark with bonus:', format(total_with_bonus, '.1f'))
else:
print('Total mark with bonus:', format(total_with_bonus, '.1f'))
print()
outFile = open("TestFile.txt", "w")
outFile.write("student \t student \t A1 \t A2 \t final \t weighted \t weighted total\n" )
outFile.write("id \t name \t \t exam \t total \t with bonus\n")
outFile.write("-----------------------------------------------------------------------------------------------\n")
outFile.close()
content = str(studentID) + "\t" "\t" + str(studentname) + "\t" + str(assignment1) + "\t" + str(assignment2) + "\t" + str(final_exam) + "\t" + str(weightedtotal)
outFile = open("TestFile.txt", "a")
outFile.write(content)
outFile.close()
#Displays Goodbye. message
print('Goodbye.')
How about something like this pattern:
while True:
# Your code here
if enter_more_data == 'N':
break