How to raw_input data when using user defined functions: - python

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

Related

How would I round the output of the code?

I'm new to programming (Just started yesterday) and I was trying to make a calculator that when given input for the variables, it would come up with the number. It worked fine, but I wanted to make it so that the output that the code had at the end would be rounded. How would I round the output of the code?
print("What is the Initial Principal Value?")
P = int(input())
print("What is the interest rate?")
r = float(input())
print("What is the number of times interest is applied per time period")
n = int(input())
print("Finally, what is the number of time periods elapsed, this must be typed in terms of annual circumstances.")
t = int(input())
print(P*(1+(r/n))**(n/t))
round()
Here it is:
print("What is the Initial Principal Value?")
P = int(input())
print("What is the interest rate?")
r = float(input())
print("What is the number of times interest is applied per time period")
n = int(input())
print("Finally, what is the number of time periods elapsed, this must be typed in terms of annual circumstances.")
t = int(input())
result = round(P * (1 + (r / n)) ** (n / t), 2)
print(result)

How to Define Parameters Outside of a Function Loop?

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!')

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

Multiple parameters definition of a function 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.

Categories