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
Related
I'm trying to calculate the number of rolls it takes to go broke, and the amount of rolls that would have left you with the most money. The program is split into several functions outside of main (not my choice) so that makes it more difficult for me.
I'm very new to python, and this is an exercise for school. I'm just not really sure where to go from here, and I realize I'm probably doing some of this wrong. Here's the code I have so far:
import random
def displayHeader(funds):
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
funds = int(input("How many dollars do you have? "))
def rollDie(newFunds):
#this function is supposed to simulate the roll of two die and return results
while funds > 0:
diceRoll = random.randint(1,6)
totalRoll = (diceRoll + diceRoll)
if totalRoll == 7:
funds = funds + 4
else:
funds = funds - 1
if funds == 0:
newFunds = funds
def displayResults():
#this function is supposed to display the final results.
#the number of rolls, the number of rolls you should have stopped at, and the max amount of money you would have had.
def main():
#everything gathered from the last function would be printed here.
main()
import random
maxmoney = []
minmoney = []
def displayHeader():
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
funds = int(input("How many dollars do you have? "))
return funds
def rollDie():
#this function is supposed to simulate the roll of two die and return results
funds = displayHeader()
while funds > 0:
diceRoll1 = random.randint(1,6)
diceRoll2 = random.randint(1,6)
totalRoll = (diceRoll1 + diceRoll2)
if totalRoll == 7:
funds = funds + 4
maxmoney.append(funds)
else:
funds = funds - 1
minmoney.append(funds)
def displayResults():
#this function is supposed to display the final results.
#the number of rolls, the number of rolls you should have stopped at, and the max amount of money you would have had.
rollDie()
numOfRolls = len(maxmoney) + len(minmoney)
numOfRolls2Stop = (len(maxmoney) - 1 - maxmoney[::-1].index(max(maxmoney))) + (len(minmoney) - 1 - minmoney[::-1].index(max(maxmoney)-1)) + 1 if maxmoney and minmoney else 0
maxAmount = max(maxmoney) if maxmoney else 0
return numOfRolls, numOfRolls2Stop, maxAmount
def main():
#everything gathered from the last function would be printed here.
a, b, c = displayResults()
print('The number of total rolls is : ' + str(a))
print("The number of rolls you should've stopped at is: " + str(b))
print("The maximun amount of money you would've had is: $" + str(c))
main()
Your program use variables that can only be accessed in certain scopes, so I think that the most recommended thing is that you use a class.
displayHeader input method it could stop the execution of the program since if you do not introduce a numerical value it will raises an exception called ValueError, if this does not help you much, I advise you to read the code carefully and add missing variables such as the input amount and the final amount and others...
class rollDiceGame():
def __init__(self):
self.funds = 0
self.diceRollCount = 0
def displayHeader(self):
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
self.funds = int(input("How many dollars do you have? "))
def rollDice(self):
while self.funds > 0:
diceRoll = random.randint(1,6)
totalRoll = (diceRoll + diceRoll)
self.diceRollCount += 1
if totalRoll == 7:
self.funds += 4
else:
self.funds -= 1
def displayResult(self):
print('Roll count %d' % (self.diceRollCount))
print('Current funds %d' % (self.funds))
def main():
test = RollDiceGame()
test.displayHeader()
test.rollDice()
test.displayResult()
main()
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'm in a beginner Python class and my instructor wrote pseudocode for us to follow. I've followed it to a T (I feel) and have been getting bugs no matter how I try changing the program. I'd rather have my mistake quickly pointed out than spend more time mucking about. This is written in Python 2.7.8.
#Anthony Richards
#25 February 2018
#This program is a simple simulation of an order-taking software.
#It demonstrates multiple variables, functions, decisions, and loops.
def main():
declareVariables()
while keepGoing == "y":
resetVariables()
while moreFood == "y":
print "Enter 1 for Yum Yum Burger"
print "Enter 2 for Grease Yum Fries"
print "Enter 3 for Soda Yum"
option = input("Please enter a number: ")
if option == 1:
getBurger()
elif option == 2:
getFries()
elif option == 3:
getSoda()
else:
print "You've made an incorrect entry. Please try again."
moreFood = raw_input("Would you like to order anything else? (y/n): ")
calcTotal(totalBurger, totalFries, totalSoda)
printReceipt(total)
keepGoing = raw_input("Would you like to place another order? (y/n): ")
def declareVariables():
keepGoing = "y"
moreFood = "y"
totalBurger = 0
totalFries = 0
totalSoda = 0
subtotal = 0
tax = 0
total = 0
option = 0
burgerCount = 0
fryCount = 0
sodaCount = 0
def resetVariables():
totalBurger = 0
totalFries = 0
totalSoda = 0
total = 0
tax = 0
def getBurger(totalBurger):
burgerCount = input("Please enter the number of burgers: ")
totalBurger = totalBurger + burgerCount * .99
def getFries(totalFries):
fryCount = input("Please enter the number of fry orders: ")
totalFries = totalFries + fryCount * .79
def getSoda(totalSoda):
sodaCount = input("Please enter the number of drinks: ")
totalSoda = totalSoda + sodaCount * 1.09
def calcTotal(totalBurger, totalFries, totalSoda):
subtotal = totalBurger + totalFries + totalSoda
tax = subtotal * .06
total = subtotal + tax
def printReceipt(total):
print "Your total is $"+str(total)
main()
def func():
x = "this is not global"
func()
# print(x) would throw an error
def func2():
global y
y = "this is global"
func2()
print(y) # This indeed will print it
Although you can use this, this is very, very bad practise.
Scopes. You define the variables, but they only exist in declareVariables. Simply move the references over to inside the function you want (main) so they can exist there. Better yet, merge all the functions into one big one, so you don't have to worry about this (or have them all exist in the global scope [defining them before any functions are defined])
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
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