Mismatch but don't know what is wrong...(python) - 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

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

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

Python CD annual precentage

I am doing this assignment. when i input the number of months it is one printing one month. rather it be 5 months or 17 months its only printing 1 months total.
https://drive.google.com/file/d/0B_K2RFTege5uZ2M5cWFuaGVvMzA/view?usp=sharing
Here is what i have so far what am i over looking thank you
calc = input('Enter y or n to calculate your CDs worth?')
month= int(input('Select your number of months'))
while calc == 'y':
while month > 0:
amount = int(input('Please enter the amount:'))
percent= float(input('Please enter the annual percentage:'))
calc= amount + amount* percent/ 1200
print(calc)
You would want to use a for loop rather than while in this sense since you are doing a set amount of operations. You also were reusing calc and assigning calc to from a String to a float, generally a bad idea. The main problem is the formula builds upon the previously calculated number, it starts off with the initial amount entered, 10000 + 10000 * 5.75 / 1200 = 10047.91, then uses 10047.91 in the next calculation, instead of 10000, you never were reusing the previously calculated number, so you weren't getting the right answer. This should do it:
calc = input('Enter y or n to calculate your CDs worth?')
if calc == 'y':
month = int(input('Select your number of months'))
amount = int(input('Please enter the amount:'))
percent = float(input('Please enter the annual percentage:'))
for i in range(month):
if i == 0:
calcAmount = amount + ((amount * percent) / 1200)
else:
calcAmount = calcAmount + ((calcAmount * percent) / 1200)
print calcAmount

Categories