if statement ignored in python - python

I have the following code:
For some reason, the program ignores the 2nd 'if' statement.
Does anyone have any idea why, please?
#define function
def CalculateBasicPay (hours, rate):
pay = hours * rate
return pay
def CalculateOvertimePay (overtime_hours, overtime_rate):
overtime = overtime_hours * overtime_rate * 1.5
return overtime
#main program to get user input
hoursWorked = int()
if hoursWorked < 40:
converted_hours = float(input("Enter number of hours: "))
converted_rate = float(input("Enter your rate: "))
totalHours = CalculateBasicPay(converted_hours,converted_rate)
print("Your total pay is: £", totalHours)
if hoursWorked > 40:
converted_hours = float(input("Enter number of hours: "))
converted_rate = float(input("Enter your rate: "))
totalHours2 = CalculateOvertimePay(converted_hours,converted_rate)
print("Your total pay is: £", totalHours2)
----------
The output is only taking the 1st condition always:
Enter number of hours: 5
Enter your rate: 2
Your total pay is: £ 10.0
>>>
Enter number of hours: 50
Enter your rate: 2
Your total pay is: £ 100.0
-----------
I'm brand-new to python! So please be nice :)
Cheers :)

You should get the hours worked outside the if statement:
#define function
def CalculateBasicPay (hours, rate):
pay = hours * rate
return pay
def CalculateOvertimePay (overtime_hours, overtime_rate):
overtime = overtime_hours * overtime_rate * 1.5
return overtime
#main program to get user input
hoursWorked = float(input("Enter number of hours: "))
converted_rate = float(input("Enter your rate: "))
if hoursWorked < 40:
totalHours = CalculateBasicPay(converted_hours,converted_rate)
print("Your total pay is: £", totalHours)
if hoursWorked > 40:
totalHours2 = CalculateOvertimePay(converted_hours,converted_rate)
print("Your total pay is: £", totalHours2)

Your line hoursWorked = int() doesn't get an input from the user, it just creates an integer with the value 0.
You should replace it with something like:
hoursWorked = int(input("How many hours have you worked: "))

Related

How to fix the "TypeError: can only concatenate str (not "float") to str"

We were given a fairly simple flowchart to convert into Python, asking us for employee name, hourly rate, hours worked, deduction, gross pay, and net pay. Afterwards, we have to then print the employee's name along with their netpay. The problem I encountered is that this error, "TypeError: can only concatenate str (not "float") to str" always appears.
`employee_name = input("Enter employee name: ")
employee_name = str(employee_name)
hourly_rate = float(input("Enter hourly rate: "))
hours_worked = float(input("Enter hours worked: "))
deduction = float(input("Enter amount of deduction: "))
net_pay = hours_worked * hourly_rate
net_pay = str(net_pay)
gross_pay = net_pay - deduction
print(employee_name + " has a net pay of " + str(net_pay))`
I've been told that I just have to net_pay to str, but I don't exactly know what that means. Thank you in advance for anyone willing to assist me in this matter. As my username says, I'm a college freshman and we were given this assignment without being taught anything about solving Python problems.
The following code will work and probably do what you want:
employee_name = input("Enter employee name: ")
hourly_rate = float(input("Enter hourly rate: "))
hours_worked = float(input("Enter hours worked: "))
deduction = float(input("Enter amount of deduction: "))
net_pay = hours_worked * hourly_rate
gross_pay = net_pay - deduction
print(employee_name + " has a net pay of " + str(net_pay))
I removed the line where employee_name is converted to str. It didn't hurt but was just superfluous and as it is already a str.
The problem was the other line I removed where you converted net_pay to str but did computations on it later when you computed gross_pay.
This way, net_pay is converted to str only when printing it.
Note that gross_pay is never used in your example.
Before concatenating the strings, you must convert the net pay variable to a string,
Like so:
employee_name = input("Enter employee name: ")
employee_name = str(employee_name)
hourly_rate = float(input("Enter hourly rate: "))
hours_worked = float(input("Enter hours worked: "))
deduction = float(input("Enter amount of deduction: "))
net_pay = hours_worked * hourly_rate
gross_pay = net_pay - deduction
print(employee_name + " has a net pay of " + str(net_pay))
We use str() to convert net pay to a string before concatenating it with the other strings.
The mistake you made is that you wanted to calculate with a string, but you can't because python sees a string as text and not as numbers. So you have to calculate with a float, he sees this as numbers.
I hope this explanation helped you a bit.
Have a nice day.
employee_name = input("Enter employee name: ")
employee_name = str(employee_name)
hourly_rate = float(input("Enter hourly rate: "))
hours_worked = float(input("Enter hours worked: "))
deduction = float(input("Enter amount of deduction: "))
#here you create 2 net_pay's, one is a string (string = text so to print), the other is a float (float = number so you can calculate with)
net_payFloat = hours_worked * hourly_rate
net_payString = str(net_payFloat)
gross_pay = net_payFloat - deduction
#here you don't need to make a string of net_pay because, you already have one named net_payString
print(employee_name + " has a net pay of " + net_payString)
`employee_name = input("Enter employee name: ")
employee_name = str(employee_name)
hourly_rate = float(input("Enter hourly rate: "))
hours_worked = float(input("Enter hours worked: "))
deduction = float(input("Enter amount of deduction: "))
net_pay = hours_worked * hourly_rate
#net_pay = str(net_pay) <------- remove this line
gross_pay = net_pay - deduction
print(employee_name + " has a net pay of " + str(net_pay))`
You are converting net_pay variable to string and applying math operation on that string. That's why you getting the error. You don't need that line, you can convert it only when you are printing.

Trying to calculate the amount of tax someone needs to pay based on age

This is my current code, and I'm trying to calculate the amount of tax someone needs to pay based on their age. The calculations are right, but I keep getting errors.
#Get the Age of from user input
from datetime import datetime, date
print("Please enter your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(date_of_birth)
print("You are " ,int(age), " years old.")
#Get the Salary from user input
def get_salary():
while True:
try:
salary = int(input("Please enter your salary: "))
except ValueError:
print("You need to enter a number ")
else:
break
return salary
#Calculate the Amount that needs to be paid, using if,elif,else
def contribution(age):
if age <= 35:
tax = (salary * 0.20)
elif 36 <= age <= 50:
tax = (salary * 0.20)
elif 51 <= age <= 55:
tax = (salary * 0.185)
elif 56 <= age <= 60:
tax = (salary * 0.13)
elif 61 <= age <= 65:
tax = (salary * 0.075)
else:
tax = (salary * 0.05)
return tax
#Print the amount
if __name__ == "__main__":
salary = get_salary
tax = contribution(age)
print("you have to pay", tax, " every month.")
This is the error that keeps popping up:
Please enter your date of birth (dd mm yyyy)
--->01 08 1946
You are 74 years old.
Traceback (most recent call last):
File "/Users/mikael/Age-TaxCalculator.py", line 46, in <module>
tax = contribution(age)
File "/Users/mikael/Age-TaxCalculator.py", line 39, in contribution
tax = (salary * 0.05)
TypeError: unsupported operand type(s) for *: 'function' and 'float'
>>>
When the program ends, I would like it to prompt the user if he/she needs to do another calculation. After researching for hours trying to find a solution, do I move the whole main code into this function?
while True:
#input the whole code
while True:
answer = str(input("Do you need to do another calculation? (y/n): "))
if answer in ("y", "n"):
break
print "invalid input."
if answer == "y":
continue
else:
print("Thank you, Goodbye")
break
This should do the trick:
#Get the Age of from user input
from datetime import datetime, date
#define functions before main script
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
#Calculate the Amount that needs to be paid, using if,elif,else
def contribution(age):
if age <= 35:
tax = (salary * 0.20)
elif 36 <= age <= 50:
tax = (salary * 0.20)
elif 51 <= age <= 55:
tax = (salary * 0.185)
elif 56 <= age <= 60:
tax = (salary * 0.13)
elif 61 <= age <= 65:
tax = (salary * 0.075)
else:
tax = (salary * 0.05)
return tax
#run until close = True
close = False
while close = False:
print("Please enter your date of birth (dd mm yyyy)") #get age input
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
age = calculate_age(date_of_birth) #get age from function calculate_age()
print("You are " ,int(age), " years old.")
#Get the Salary from user input
while not salary.is_integer(): #keep asking for salary until it is an int
salary = int(input("Please enter your salary: "))
if not salary.is_integer(): #if the salary inputed is an int it will skip this next step
print("You need to enter a number!")
salary = get_salary() #get salary from get_salary()
tax = contribution(age) #calculate the tax
print("you have to pay", tax, " every month.")
ask = input("Do you need another calculation?") #if ask is yes close will stay as false and the script will just run again
if ask == 'yes' or ask == 'y':
return
elif ask == 'no' or ask == 'n': #if ask is no, close will be set to True closing the script
close = True

How do you get the tax value to print without overtime

user = str
end = False
hours = round(40,2)
print("How much do you make?")
while end == False:
user = input("\nPlease enter your name or type '0' to quit: ")
if user == "0":
print("End of Report")
break
else:
hours = (float(input("Please enter hours worked: ", )))
payrate =(float(input("Please enter your payrate: $", )))
taxrate = (float(input ("Please enter tax rate: ")))
if hours <= 40:
print(user)
print("Overtime hours: 0")
print("Overtime Pay: $0.00")
regularpay = round(hours * payrate, 2)
print("Gross Pay: $", regularpay)
elif hours > 40:
overtimehours = round(hours - 40.00,2)
print("Overtime hours: ", overtimehours)
print("Employee's name: ", user)
regularpay = round(hours * payrate,2)
overtimerate = round(payrate * 1.5, 2)
overtimepay = round(overtimehours * overtimerate)
if overtimepay == 0:
grosspay = round(regularpay,2)
else overtimepay > 0:
grosspay = round(regularpay+overtimepay,2)
income = (grosspay * taxrate)
print("Regular Pay: $", regularpay)
print("Overtime Pay: $",overtimepay)
print("Gross Pay: $", grosspay)
print ("Income: $", income)
I added that extra If/Else statement to hopefully force it it through but that still didnt seem to get it to work. Even if you remove the second else if statement it still does not get it to print, only when you do have over time then it factors in the tax rate.
You only set overtimepay when you actually process overtime. Undefined variables in python are not 0. They are a special value None. Therefore if no overtime was worked, neither of your ifs evaluates to True and neither branch gets executed.

Python: How to use user input to close or continue a while loop

I am new to python, and still trying to figure out the basics. I've looked for an answer online, but no solutions seem to work for me. I don't know if I'm missing something small, or my total structure is wrong. The calculation portion of my code works like it's supposed to.
My problem is, I can't figure out how to ask the user to input yes or no resulting in:
(the answer YES restarting the loop so the user can try another calculation)
(the answer NO closing the loop/ending the program)
Please let me know what you suggest!
play = True
while play:
hours = float(input("Please enter the number of hours worked this week: "))
rate = float(input("Please enter your hourly rate of pay: "))
#if less than 40 hrs
if hours <= 40:
pay = hours * rate
print "Your pay for this week is",pay
#overtime 54hrs or less
elif hours > 40 < 54:
timeandhalf = rate * 1.5
pay = (40 * hours * rate) + ((hours - 40) * timeandhalf)
print "Your pay for this week is",pay
#doubletime more than 54hrs
elif hours > 54:
timeandhalf = rate * 1.5
doubletime = rate * 2
pay = (40 * hours * rate) + ((hours - 40) * timeandhalf) + ((hours - 54) * doubletime)
print "Your pay for this week is",pay
answer = (input("Would you like to try again?: "))
if str(answer) == 'yes':
play = True
else:
play = False
You are use Python 2.x. input() tries to run the input as a valid Python expression. When you enter a string, it tries to look for it in the namespace, if it is not found it throws an error:
NameError: name 'yes' is not defined
You should not use input to receive unfiltered user input, it can be dangerous. Instead, use raw_input() that returns a string:
play = True
while play:
hours = float(raw_input("Please enter the number of hours worked this week: "))
rate = float(raw_input("Please enter your hourly rate of pay: "))
#if less than 40 hrs
if hours <= 40:
pay = hours * rate
print "Your pay for this week is",pay
#overtime 54hrs or less
elif hours > 40 < 54:
timeandhalf = rate * 1.5
pay = (40 * hours * rate) + ((hours - 40) * timeandhalf)
print "Your pay for this week is",pay
#doubletime more than 54hrs
elif hours > 54:
timeandhalf = rate * 1.5
doubletime = rate * 2
pay = (40 * hours * rate) + ((hours - 40) * timeandhalf) + ((hours - 54) * doubletime)
print "Your pay for this week is",pay
answer = raw_input("Would you like to try again?: ").lower()
while True:
if answer == 'yes':
play = True
break
elif answer == 'no':
play = False
break
else:
answer = raw_input('Incorrect option. Type "YES" to try again or "NO" to leave": ').lower()
I think you should ask user to input yes or no untill he does it.
while play:
# Here goes your code
while True:
answer = input("Would you like to try again? Yes or No?").lower()
if answer in ('yes', 'no'):
break
play = answer == 'yes'
var = raw_input("Would you like to try again: ")
print "you entered", var
Variations for yes/no can be found in this question and Vicki Laidler's answer for it.

How do format my output to 2 decimal places in Python?

I'm trying to format my output into 2 decimal places in Python..This is my code
def introduction():
print("This calculator calculates either the Simple or Compound interest of an given amount")
print("Please enter the values for principal, annual percentage, number of years, and number of times compounded per year")
print("With this information, we can provide the Simple or Compound interest as well as your future amount")
def validateInput(principal, annualPercntageRate, numberOfYears,userCompound):
if principal < 100.00:
valid = False
elif annualPercntageRate < 0.001 or annualPercntageRate > .15:
valid = False
elif numberOfYears < 1:
valid = False
elif userCompound != 1 and userCompound != 2 and userCompound != 4 and userCompound != 6 and userCompound != 12:
valid = False
else:
valid = True
return valid
def simpleInterest(principal, annualPercentageRate, numberOfYears):
return (principal * annualPercentageRate * numberOfYears)
def compoundInterest(principal, annualPercentageRate, numberOfYears, userCompound):
return principal * ((1 + (annualPercentageRate / userCompound))**(numberOfYears * userCompound) - 1)
def outputAmounts(principal, annualPercentageRate, numberOfYears, userCompound, simpleAmount,compoundAmount):
print("Simple interest earned in", numberOfYears, "will be $",simpleAmount,"making your future amount $",(principal + simpleAmount)
print("Interest compounded", userCompound, "in",numberOfYears, "will earn $",compoundAmount,"making your future amount",(principal + compoundAmount)
def main():
introduction()
principal = float(input("Enter principal: "))
annualPercentageRate = float(input("Enter rate: "))
numberOfYears = int(input("Enter years: "))
userCompound = int(input("Enter compounding periods: "))
if validateInput(principal, annualPercentageRate, numberOfYears, userCompound):
simpleAmount = simpleInterest(principal, annualPercentageRate, numberOfYears)
compoundAmount = compoundInterest(principal, annualPercentageRate, numberOfYears, userCompound)
outputAmounts(principal, annualPercentageRate, numberOfYears, userCompound, simpleAmount,compoundAmount)
else:
print("Error with input, try again")
main()
So for my output, I want to format the ending to 2 decimal places. Namely, these 2 variables
-(principal + compoundAmount)
-(principal + simpleAmount)
I know I need to use %.2, but Im not sure how to add that into a print statement so that it would output into 2 decimal places...How do I do this?
try this
print('pi is {:.2f}'.format(your_variable))
You just need simple formatting string, like:
print('pi is %.2f' % 3.14159)
which output is pi is 3.14
You might wanna read https://docs.python.org/2.7/library/string.html#formatspec

Categories