How to Define Parameters Outside of a Function Loop? - python

I am trying to execute a function that will repeat if given the right input as seen in my while statement. However my program returns the same value in additional loops without option to use new hrs and rate inputs if my input statements are above my function. If they are within the function as currently presented, it states my (hrs,rate) is not defined. How would I define the hrs and rate parameters while keeping my inputs within the function?
def CalPay(hrs,rate):
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
try:
hrs = float(hrs)
except:
hrs = -1
try:
rate = float(rate)
except:
rate = -1
if hrs <= 0 :
print('You have entered wrong information for hours.')
elif rate <= 0 :
print('You have entered wrong rate information.')
elif hrs <= 40 :
pay = hrs * rate
print ('Your pay for this week is:', pay)
elif hrs > 40 and hrs < 60 :
pay = ((hrs - 40) * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
elif hrs >= 60 :
pay = ((hrs - 60) * (rate * 2.0)) + (20 * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
while True:
CalPay(hrs,rate)
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')

First, you need to initialize the two variables after the function, so whenever the time you enter the variables' values, they've to be defined.
Something like that:
# those two lines will be after the function
hrs = 0
rate = 0
Full program will go like that: -
def CalPay(hrs,rate):
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
try:
hrs = float(hrs)
except:
hrs = -1
try:
rate = float(rate)
except:
rate = -1
if hrs <= 0 :
print('You have entered wrong information for hours.')
elif rate <= 0 :
print('You have entered wrong rate information.')
elif hrs <= 40 :
pay = hrs * rate
print ('Your pay for this week is:', pay)
elif hrs > 40 and hrs < 60 :
pay = ((hrs - 40) * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
elif hrs >= 60 :
pay = ((hrs - 60) * (rate * 2.0)) + (20 * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
hrs = 0
rate = 0
while True:
CalPay(hrs,rate)
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
OUTPUT
Please enter number of hours worked for this week: 36
What is hourly rate: 6
Your pay for this week is: 216.0
Do you wish to repeat this program? (y/n)Y
Please enter number of hours worked for this week: 12
What is hourly rate: 5
Your pay for this week is: 60.0
Do you wish to repeat this program? (y/n)

In your while loop you call CalPay and pass in hrs and rate. You are calling a function and giving it two values that you create inside of the function i.e. they don't exist when you call CalPay, so you get an error. Just collect the inputs in your while loop instead of inside your function. Like this:
while True:
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
CalPay(hrs,rate)
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
Note: You'll have to adjust the logic for repeating the program accordingly.
Another even better solution would be to remove the arguments from CalPay and the function call and then collect the information you need inside the function. As mentioned by Anurag.
def CalPay():
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
try:
hrs = float(hrs)
except:
.
.
.
while True:
CalPay()
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')

Related

future value of monthly investments calculator with user input - Python

I am trying to write a program that will calculate the future value of a monthly investment. Here is what I have so far:
def get_number(prompt, low, high):
while True:
number = float(input(prompt))
if number > low and number <= high:
is_valid = True
return number
else:
print("Entry must be greater than", low,
"and less than or equal to", high,
"Please try again.")
def get_integer(prompt, low, high):
while True:
number = int(input(prompt))
if number > low and number <= high:
is_valid = True
return number
else:
print("Entry must be greater than", low,
"and less than or equal to", high,
"Please try again.")
def calculate_future_value(monthly_investment, yearly_interest, years):
# convert yearly values to monthly values
monthly_interest_rate = ((yearly_interest / 100) + 1) ** (1 / 12)
months = years * 12
# calculate future value
future_value = 0.0
for i in range(1, months):
future_value += monthly_investment
monthly_interest = (future_value * monthly_interest_rate)-future_value
future_value += monthly_interest
return future_value
def main():
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = get_number("Enter monthly investment:\t", 0, 1000)
yearly_interest_rate = get_number("Enter yearly interest rate:\t", 0, 15)
years = get_integer("Enter number of years:\t\t", 0, 50)
# get and display future value
future_value = calculate_future_value(
monthly_investment, yearly_interest_rate, years)
print("Future value:\t\t\t" + str(round(future_value, 2)))
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print("Bye!")
if __name__ == "__main__":
main()
Everything in the program is working fine except for the def calculate_future_value(monthly_investment, yearly_interest, years): section I believe I have a logic error but I can't find exactly what's going wrong.
The output should look like this
Enter monthly investment: 350
Enter yearly interest rate: 10
Enter number of years: 36
Future value: 1484636.15
Continue? (y/n): n
Bye!
But im getting
Enter monthly investment: 350
Enter yearly interest rate: 10
Enter number of years: 36
Future value: 1312573.73
Continue? (y/n): no
Bye!
In testing out your code, I believe you really only need to correct one formula. The following statement does not appear to be correct.
monthly_interest_rate = ((yearly_interest / 100) + 1) ** (1 / 12)
That would appear to raise your yearly interest rate to the "1/12th" power and not divide it into 1/12th of the yearly interest. I revised that formula as follows:
monthly_interest_rate = ((yearly_interest / 12 / 100) + 1)
When I ran the program the value came out close to what you noted in your issue.
#Dev:~/Python_Programs/Investment$ python3 Invest.py
Enter monthly investment: 350
Enter yearly interest rate: 10
Enter number of years: 36
Future value: 1472016.43
Continue? (y/n): n
Bye!
The difference between this value and the value you stated might be attributable to actually having the interest compounded daily each month.
But you might give this tweak a try and see if it meets the spirit of your project.

Python: for loop with counter and scheduled increase in increase

Python Learner. Working on a recurring monthly deposit, interest problem. Except I am being asked to build in a raise after every 6th month in this hypothetical. I am reaching the goal amount in fewer months than I'm supposed to.
Currently using the % function along with += function
annual_salary = float(input("What is your expected Income? "))
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment= total_cost*.25
savings = 0
for i in range(300):
savings = monthly_savings*(((1+.04/12)**i) - 1)/(.04/12)
if float(savings) >= down_payment:
break
if i % 6 == 0 :
monthly_salary += monthly_salary * .03
monthly_savings = monthly_salary * portion_saved
Thanks for the advice all. My code is getting clearer and I reached correct outputs! The problem was with how and when I was calculating interest. In the case of a static contribution I successfully used the formula for interest on a recurring deposit, here, the simpler move of calculating interest at each month was needed to work with the flow of the loop.
annual_salary = float(input("What is your expected Income? "))
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment = total_cost*.25
savings = 0
month = 1
while savings < down_payment :
print(savings)
savings += monthly_savings
savings = savings * (1+(.04/12))
month += 1
if month % 6 == 0 :
monthly_salary += (monthly_salary * semi_annual_raise)
monthly_savings = (monthly_salary * portion_saved)
print("")
print("it will take " + str(month) + " months to meet your savings goal.")
Does something like this work for you? Typically, we want to use while loops over for loops when we don't know how many iterations the loop will ultimately need.
monthly_savings = 1.1 # saving 10% each month
monthly_salary = 5000
down_payment = 2500
interest = .02
savings = 0
months = 0
while savings < goal:
print(savings)
savings = (monthly_salary * monthly_savings) + (savings * interest)
months += 1
if months % 6 == 0 :
monthly_salary += monthly_salary * .03
print("Took " + str(months) + " to save enough")

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 -------------^

Mismatch but don't know what is wrong...(python)

So I need help with programming.
My assignment is this:
Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use raw_input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.
I did this:
inp = raw_input ('Enter Hours: ')
hours = float(inp)
inp = raw_input ('Enter Rate: ')
rate = float(inp)
print rate, hours
if hours <= 40 :
pay = hours * rate
else :
pay = rate * 40 + (rate * 1.5 * ( hours - 40 ))
print pay
And it seemed to be okay but when I click on check the code, I enter hours 45, and then rate I tried entering 10.50, 10.5 but every time I get this:
10.5 45.0 ← Mismatch
498.75
The answer 498.75 is correct but I keep getting mismatch there so I cannot finish my assignment. Anyone knows what am i doing wrong?
To print float with your format you should use format string (examples).
So you should change line:
print rate, hours
to:
print("Rate = %.2f, Hours = %.0f" % (rate, hours))
# ^ ^
# | Remove all chars after point (may be you need to change that
# according your task)
# Use to chars after comma (no zeros removing)
By using a function you can do it
def computepay(h,r):
if (h>40) :
pay = (40*r)+(h-40)*1.5*r
else:
pay = (h*r)
return pay
try:
inp = raw_input("Please enter hours: ")
hours=float(inp)
inp = raw_input("Please enter rate: ")
rate= float(inp)
except:
print "Please enter a number as input"
quit()
print computepay(hours,rate)
It seems that print rate, hours produces output which the checking program does not expect, and cannot cope with. Simply comment out that line.
hrs = raw_input("Enter Hours:")
h = float(hrs)
rate = raw_input("Enter rate:")
r = float(rate)
pay = h * r
print pay
This would be the answer to your question #user3578390
4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your variable sum or use the sum() function.
def computepay(h,r):
if h <= 40:
return h * r
elif h > 40:
return (40 * r + ((h - 40) * 1.5 * r))
hrs = float(input("Enter Hours:"))
rate = float(input("Enter Rate:"))
p = computepay(hrs, rate)
print("Pay",p)
I did this:
hrs = raw_input("Enter Hours:")
h = float(hrs)
rate = raw_input("Enter rate:")
r = float(rate)
pay = h * r
if h <=40:
pay = h * r
else:
pay = r * 40 + (r * 1.5 * ( h - 40 ))
print pay

Categories