Multiple parameters definition of a function Python - python

I'm trying to write a function that calculates the cost of a loan, but I keep getting the cost of the loan to be the negative value of what the user inputs as the amount of the loan.
#define monthly payment
def MonthlyPayment (ammountOfLoan, numberOfPeriods,yearlyInterestRate):
ammountOfLoan = 0
numberOfPeriods = 0
yearlyInterestRate = 0
payment = [(yearlyInterestRate/12)/(1-(1+yearlyInterestRate/12))**(-numberOfPeriods)] * ammountOfLoan
return (payment)
#define cost of loan
def LoanCost(principal, month, payment):
period = 0
month = 0
payment = 0
cost = period * payment - principal
return (cost)
#calculate cost of loan
def main():
loan = float(raw_input("What is the ammount of your loan? "))
period = float(raw_input("How many months will you make payments? "))
rate = float(raw_input("What is the interest rate? "))
rate = rate / 100
MonthlyPayment(loan, period, rate)
costOfLoan = LoanCost(loan, period, rate)
print "The cost of the loan is $" + str(costOfLoan)
#run main
main()

LoanCost is setting period and payment to 0 (you're making the same mistake in MonthlyPayment, as well), then multiplying them. So you're ending up with (0 * 0) - principal. You're also calling the second parameter "month", when what you really mean is "period".
Just to clarify, when you have a function definition like
def func(a, b, c):
You shouldn't initialize a, b, and c to zero inside the function body. You're overwriting their values when you do that. Just use them directly.

Related

Unsure why output is 0. Trying to count months to pay downpayment

print("Please enter you starting annual salary: ")
annual_salary = float(input())
monthly_salary = annual_salary/12
print("Please enter your portion of salary to be saved: ")
portion_saved = float(input())
print ("Please enter the cost of your dream home: ")
total_cost = float(input())
current_savings = 0
r = 0.04/12
n = 0
portion_down_payment = total_cost*int(.25)
if current_savings < portion_down_payment:
monthly_savings = monthly_salary*portion_saved
interest = monthly_savings*r
current_savings = current_savings + monthly_savings + interest
n =+ 1
else:
print(n)
The above is my code. I keep getting output = 0 but unsure why.
This the problem statement, I am a HS student attempting OCW coursework.
Call the cost of your dream home ​total_cost​.
Call the portion of the cost needed for a down payment ​portion_down_payment​. For simplicity, assume that portion_down_payment = 0.25 (25%).
Call the amount that you have saved thus far ​current_savings​. You start with a current savings of $0.
Assume that you invest your current savings wisely, with an annual return of ​r ​(in other words, at the end of each month, you receive an additional ​current_savings*r/12​ funds to put into your savings – the 12 is because ​r​ is an annual rate). Assume that your investments earn a return of r = 0.04 (4%).
Assume your annual salary is ​annual_salary​.
Assume you are going to dedicate a certain amount of your salary each month to saving for the down payment. Call that ​portion_saved​. This variable should be in decimal form (i.e. 0.1 for 10%).
At the end of each month, your savings will be increased by the return on your investment, plus a percentage of your ​monthly salary ​(annual salary / 12). Write a program to calculate how many months it will take you to save up enough money for a down payment. You will want your main variables to be floats, so you should cast user inputs to floats.
Your program should ask the user to enter the following variables:
The starting annual salary (annual_salary)
The portion of salary to be saved (portion_saved)
The cost of your dream home (total_cost)
Test Case 1
Enter your annual salary:​ 120000 Enter the percent of your salary to save, as a decimal:​ .10 Enter the cost of your dream home:​ 1000000 Number of months:​ 183
You have n =+ 1 but I think you mean n += 1
Also int(.25) evaluates to 0, I think you want int(total_cost*.25). As your code is, the if statement will always evaluate to False because current_savings == 0 and portion_down_payment == 0
More generally, when your code isn't working as expected, you should put in either print() or assert statements to narrow down where your code is deviating from what you expect. For example, before the if statement you could have it print the two values you are comparing.

Python Prediction for organism population growth

The inputs would be:
The initial number of organisms
The rate of growth (a real number greater than 1)
The number of hours it takes to achieve this rate
A number of hours during which the population grows
I have:
Population = int(input("The initial number of organisms: " ))
RateOfGrowth = int(input("The rate of growth (a real number > 0): " ))
HrToAchieve = int(input("The number of hours it takes to achieve this rate: " ))
Input_Hrs = int(input("Enter the total hours of growth: " ))
NewGrowth = 0
Passes = Input_Hrs/HrToAchieve
while Passes > 0:
NewGrowth = (Population * RateOfGrowth)-Population
Population += NewGrowth
Passes -= 1
print("The total population is", Population )
New at loops and not sure how I'm missing a pass
partially working with input 10,2,2,6 providing correct answer of 80
But when using 100 organisms with growth rate of 5 over 2 hrs over 25 hrs total, I get 7000 NOT
24414062500 which would be proper.
You can do that in one line and Im assuming if the growth rate of x is there in y hours and there are less than y hours left, then there wont be any growth whatsoever.
import math
ORG = int(input("The initial number of organisms: " ))
GR = int(input("The rate of growth (a real number > 0): " ))
GR_Hr = int(input("The number of hours it takes to achieve this rate: " ))
PG_Hr = int(input("Enter the total hours of growth: " ))
Growth = ORG * int(math.pow(GR, PG_Hr//GR_Hr)) # or Growth = ORG * int(GR ** (PG_Hr // GR_Hr))
EDIT USING LOOPS
Growth_using_loops = ORG
loop_counter = PG_Hr//GR_Hr # double slash // returns a integer instead of float
for i in range(loop_counter):
Growth_using_loops = Growth_using_loops * GR
print(Growth)
print(Growth_using_loops)
Output :
The initial number of organisms: 100
The rate of growth (a real number > 0): 5
The number of hours it takes to achieve this rate: 2
Enter the total hours of growth: 25
24414062500
24414062500

How to raw_input data when using user defined functions:

Hi i am new to programming and just started learning python i wrote the below code /program to prompt hours and rate per hour using raw_input to compute gross pay. i tried to initiate time-and-a-half for the hourly rate for all hours worked above 40 hours. the logic to do the computation of time-and-a-half in a function called computepay() and use the function to do the computation. The function should return a value. i used 45 hours and a rate of 10.50 per hour to test the program (the pay should return 498.75). i tried using raw_input to read a string and float() to convert the string to a number. i Don't name my variable sum or use the sum() function. i am able to print the output but i need to input the data when prompted unlike inputing the value in "line16"
def computePay (hours,rate):
if hours > 40:
overtimerate = 1.5 * rate
overtime = (hours-40) * overtimerate
overtimepay = overtime + (40 * rate)
return overtimepay;
else:
normalpay = hours * rate
return normalpay;
hours = raw_input('Enter hours: ')
hrs = int(hours)
rate = raw_input('Enter rate: ')
r = float(rate)
p = computePay(45,10.50)
print p
Assumptions:
I had to make the following assumptions in understanding your question:
Looking at your print statement, You are using python2.x
You want to computePay using the user inputted hours and rate.
Problem:
In the following line you are using constant hrs and r values instead of using the user inputed values
p = computePay(45,10.50)
Solution:
If you want to use user inputted values to compute the pay, you need to call the function as follows:
p = computePay(hrs, r)
With this line you are essentially asking python to computePay using the values stored in the variables hrs and r.
Final Code:
Therefore your final code should like this:
def computePay (hours,rate):
if hours > 40:
overtimerate = 1.5 * rate
overtime = (hours-40) * overtimerate
overtimepay = overtime + (40 * rate)
return overtimepay;
else:
normalpay = hours * rate
return normalpay;
hours = raw_input('Enter hours: ')
hrs = int(hours)
rate = raw_input('Enter rate: ')
r = float(rate)
p = computePay(hrs,r)
print p
Sample Output:
Enter hours: 55
Enter rate: 20
1250.0
If you mean by that you want the arguments to equal the inputs rather than the ones inputted manually, you should do instead:
p = computePay(hrs, r)
Example output:
Enter hours: 45
Enter rate: 10.5
498.75

Calculating Compound Interest using Python functions

Write a function that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
I am having the error " ValueError: unsupported format character 'I' (0x49) at index 28"
Here is my code so far.
def BankBalance():
InputB = 1000
return InputB
print("Your initial balance is $1000")
def Interest():
InputI = 0.05
return InputI
print("The rate of interest is 5%")
def CountNumber():
InputN = float(input("Please enter the number of times per year you would like your interest to be compounded: "))
return InputN
def Time():
InputT = float(input("Please enter the number of years you need to compund interest for:"))
return InputT
def Compount_Interest(InputB, InputI, InputT, InputN):
Cinterest = (InputB*(1+(InputI % InputN))**(InputN * InputT))
print("The compound interest for %.InputT years is %.Cinterest" %Cinterest)
B = BankBalance()
I = Interest()
N = CountNumber()
T = Time()
Compount_Interest(B, I, N, T)
Here is how you would do it.
def main():
# Getting input for Balance
balance = float(input("Balance: $ "))
# Getting input for Interest Rate
intRate = float(input("Interest Rate (%) : "))
# Getting input for Number of Years
years = int(input("Years: "))
newBalance = calcBalance(balance, intRate, years)
print ("New baance: $%.2f" %(newBalance))
def calcBalance(bal, int, yrs):
newBal = bal
for i in range(yrs):
newBal = newBal + newBal * int/100
return newBal
# Program run
main()
You are trying to use your variable as a function.
Try this instead :
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
Python, and most other programming languages, don't assume that two adjacent mathematical expressions with no operator between them means multiplication. You are missing a multiplication operator (*) between InputB and the rest of the expression:
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
# Here -------------^

Fixed payment is returned as 0. Why? What corrections to make?

Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.
In this problem, we will not be dealing with a minimum monthly payment rate.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example:
Lowest Payment: 180
Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below:
Monthly interest rate = (Annual interest rate) / 12.0
Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
Here is my code. I do not know where I'm going wrong:
balance = float(raw_input('enter the outsanding balance on your card'))
annualInterestRate = float(raw_input('enter the anual interest rate as a decimal'))
month = 0
checkBalance = balance
monthlyFixedPayment = 0
while checkBalance <= 0:
checkBalance = balance
monthlyFixedPayment += 10
while month <= 11:
monthlyInterestRate = annualInterestRate/12.0
monthlyUnpaidBalance = checkBalance - monthlyFixedPayment
checkBalance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance)
print('lowest payment:' + str(monthlyFixedPayment))
I think this is the program you are looking for:
balance = 500
annualInterestRate = .5
checkBalance = balance
monthlyFixedPayment = 10
count = 0
while checkBalance > 0:
month = 0
while month <= 11 and checkBalance > 0:
count+=1
monthlyInterestRate = annualInterestRate/12.0
monthlyUnpaidBalance = checkBalance - monthlyFixedPayment
checkBalance = monthlyUnpaidBalance - (monthlyInterestRate * monthlyUnpaidBalance)
print "\t"+str(checkBalance)
month+=1
print checkBalance
print "lowest amount: "
print count*monthlyFixedPayment+checkBalance
I have left the print statements, so that you can see what is going on in each iteration.
Some problems i noticed in your code:
1) you were doing a monthlyFixedPayment += 10 that was changing the fixed payemnt. you are not supposed to change the fixed payment according to your problem definition.
2) you were doing a checkBalance = balance in each iteration of outer while loop. This was causing the calculated value to be resetted.
3) I have introduced a count variable to check how many times these decuctions were happening, as month was getting reset in each iteration.
while checkBalance <= 0: to while checkBalance >= 0:
Also, you need to increment month in the while month <= 11: loop.
You are going at it the hard way; there is an analytic solution for fixed_payment:
from math import ceil
def find_fixed_monthly_payment(balance, months, yearly_rate):
i = 1. + yearly_rate / 12.
im = i ** months
return balance * (im * (1. - i)) / (i * (1. - im))
def find_final_balance(balance, months, yearly_rate, fixed_payment):
i = 1. + yearly_rate / 12.
for _ in range(months):
# make payment
balance -= fixed_payment
# add interest
balance *= i
return balance
def get_float(prompt):
while True:
try:
return float(raw_input(prompt))
except ValueError:
# input could not be cast to float; try again
pass
def main():
balance = get_float("Please enter starting balance: ")
annual_rate = get_float("Annual interest rate (in percent): ") / 100.
fixed_payment = find_fixed_monthly_payment(balance, 12, annual_rate)
# round up to the nearest $10
fixed_payment = ceil(fixed_payment / 10.) * 10.
# double-check value of fixed_payment:
assert find_final_balance(balance, 12, annual_rate, fixed_payment ) <= 0., "fixed_payment is too low!"
assert find_final_balance(balance, 12, annual_rate, fixed_payment - 10.) > 0., "fixed_payment is too high!"
print("Lowest payment: ${:0.2f}".format(fixed_payment))
if __name__ == "__main__":
main()

Categories