How do you get the tax value to print without overtime - python

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.

Related

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

if statement ignored in 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: "))

cannot create a working loop in python

I'm so new to programming logic I'm not sure I can phrase this properly. I'm using Python 2.7 and am trying to write a script that will repeat until zero is entered. I've tried if, else, and while statements and have concluded that I don't know enough about logic to know anything about Python. For example...I'm so new that init means nothing to me. I've seen the phrase in almost every search result I've received, but I don't no what it means or is. The class I'm in is a LOGIC class not a Python class. I can write it in pseudocode but I would really like to see a working model. Please Help. This script runs through and will exit when zero is entered, but it will not prompt for miles driven again.
#Cost of Trip Ch2 Q8
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
getMiles = float(input ('Enter Miles: '))
while getMiles == 0:
print "END OF PROGRAM"
exit
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
while costOfTrip == float:
getMiles
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
Something that I forgot to mention was the mandatory "END OF PROGRAM" statement. I used a combination of your answers and this works. Again, Thank you everyone. I can stop banging my head on the wall.
#Cost of Trip Ch2 Q8
print "To Calculate the cost of your trip,"
print "enter the miles driven or enter zero to quit"
getMiles = float(raw_input ('Enter Miles: '))
while getMiles >= 0:
if getMiles == 0:
print "END OF PROGRAM"
exit()
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
getMiles = float(raw_input ('Enter Miles: '))
Python is not really that far from pseudocode, and indeed the problem here is not the code but the logic.
To get the basic "loop until entering zero" you can have the following logic:
miles = -1
while miles != 0:
miles = float(raw_input ('Enter Miles: '))
As for your own code, you seem to be using 'while' when you mean 'if'
And in the second while you are actually just naming a variable (getMiles) which does nothing
The whole code could look like this:
miles = float(raw_input ('Enter Miles: '))
while miles != 0:
fuelEcon = miles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = miles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = miles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
miles = float(raw_input ('Enter Miles: '))
** no need to use "while true" as others suggested, it's never a nice thing to do.
A more advanced version would be to extract the part of the logic which is repeatable and standalone to a function
def trip_cost(miles):
if(miles == 0):
return False
fuelEcon = miles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = miles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = miles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
return True
while trip_cost(float(raw_input ('Enter Miles: '))):
pass
As for what init is, that's a much more advanced topic of Objects Orientation which you probably shouldn't worry about just yet
I'd just say as a matter of style that even your new loop condition / logic could be quickly tidied up to read
print "To Calculate the cost of your trip,"
print "enter the miles driven or enter zero to quit"
getMiles = float(raw_input ('Enter Miles: '))
while getMiles != 0:
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
getMiles = float(raw_input ('Enter Miles: '))
print "END OF PROGRAM"
# should be no need for exit() unless code is included in a subroutine
You were very close, here is the fixed version:
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
while True:
getMiles = float(input ('Enter Miles: '))
if getMiles == 0:
print "END OF PROGRAM"
exit()
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
I added a while True around the whole block of code, this will cause the question to be asked over and over again (forever) until the user enters 0 for miles.
The only other thing that needed to be fixed was that exit is a function call so it should be exit().
total_miles = 0
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
getMiles = float(input ('Enter Miles: '))
while getMiles != 0:
total_miles = getMiles + total_miles
getMiles = float(input ('Enter Miles: '))
else:
print "END OF PROGRAM"
exit
fuelEcon = total_miles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = total_miles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = total_miles * fuelIncrease
while costOfTrip == float:
getMiles
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
You could do it like this
#Cost of Trip Ch2 Q8
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
while True:
getMiles = float(input ('Enter Miles: '))
if getMiles == 0:
print "END OF PROGRAM"
break
print 'Do the other calculations'
Go into an infinite loop until 0 is entered at which point you break out of the loop and the program ends.
You can use While 1: under python 2.7 to get faster performance, but I doubt this will be your concern at the moment.

python, stuck in infinite loop program

I am writing this python program and everything works but when I run it, I get stuck in an infinite loop. How do I fix it? thanks.
import sys
def main():
name = input("Enter your name:")
ssn = input("Enter your Social Security Number:")
income = eval(input("Enter your net income:"))
while income <= 0:
print("Error, then net income you entered is less than zero! Try again.")
income = eval(input("Enter your net income again:"))
while income > 0:
net = calc(income, name, ssn)
def calc(income, name, ssn):
if income > 15000.00:
tax = .05 * (income - 15000.00)
print(tax)
print(name)
print(ssn)
sys.exit
elif income > 30000.00:
tax = .1 * (income - 30000.00)
print(tax)
print(name)
print(ssn)
sys.exit
else:
print("There is no tax to be paid, income is in the first $15000.00")
print(name)
print(ssn)
sys.exit
main()
sys.exit is a function. You need to call it (sys.exit()) to exit the script.
The second while in your main() is not needed.
The next thing is that "sys.exit" is not right, you have to write "sys.exit()".
In your calc() function you should replace if "if income > 15000.00:" with "if income > 15000.00 and income <= 30000:" or the elif case will never get considered.
Here the correct code:
import sys
def main():
name = input("Enter your name:")
ssn = input("Enter your Social Security Number:")
income = eval(input("Enter your net income:"))
while income <= 0:
print("Error, then net income you entered is less than zero! Try again.")
income = eval(input("Enter your net income again:"))
net = calc(income, name, ssn)
def calc(income, name, ssn):
if income > 15000.00 and income <= 30000:
tax = .05 * (income - 15000.00)
print(tax)
print(name)
print(ssn)
sys.exit()
elif income > 30000.00:
tax = .1 * (income - 30000.00)
print(tax)
print(name)
print(ssn)
sys.exit()
else:
print("There is no tax to be paid, income is in the first $15000.00")
print(name)
print(ssn)
sys.exit()
main()

Python ATM Else and Elif Errors

I've been having some trouble with Else and Elif statements in Python 3.3.3 lately.
Here's my code:
# ATM was programmed by Jamie Mathieson
# introduction
sleep (1)
print ("-----------------------------------------------")
print ("\n ATM ")
print ("\n-----------------------------------------------")
sleep (3)
print ("\nWelcome to ATM. ATM is a mathematical system that handles data.")
sleep (5)
print ("\n Your ATM card has is being inserted. Please wait...")
sleep (3)
print ("Your ATM card has been inserted.")
sleep (5)
print ("Type 'options' to view available commands.")
# variables
balance = print("Balance £", money)
money = 200
options = ("Options: 1) Withdraw <amount> 2) Deposit <amount> 3) Balance 4) Exit")
# statements
option=int(input("Please enter an option: "))
if Option==1:
print("Balance £", money)
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif: Withdraw>money
print("No Balance Remaining")
else:
print("Withdraw canceled.")
if Option==3:
print("Balance £", money)
Deposit=float(input("Please enter the amount of money you would like to deposit: £ "))
if Deposit>0:
newbalance=(money+Deposit)
print("New Balance: £",newbalance)
else:
print("Deposit canceled.")
if Option==4:
print("ATM is ejecting your card. Please wait...")
sleep(5)
exit()
The error I'm getting is "invalid syntax" and it highlights both the Else and Elif statements. What is it that I'm doing wrong?
You have to put the : at the end, and correct the identation.
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif Withdraw>money:
print("No Balance Remaining")
else:
print("Withdraw canceled.")
There are several issues with the code. As #Daniel pointed out, your indentation must be corrected. Also, your condition for the elif block is placed after the colon.
Beyond that, you're assigning the user's response to a variable called option and then writing conditions on Option. Those are two different things.
Finally balance = print("Balance £", money) is going to throw an error. It looks like you're trying to define balance as a function that will print "Balance £" followed by the balance amount. If so, you could do something like this:
balance = lambda x: print("Balance £{}".format(x))
Edit: To answer your question re: sleep, use
from time import sleep
while True:
# Reading id from user
id = int(input("\nEnter account pin: "))
# Loop till id is valid
while id < 1000 or id > 9999:
id = int(input("\nInvalid Id.. Re-enter: "))
# Iterating over account session
while True:
# Printing menu
print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ")
# Reading selection
selection = int(input("\nEnter your selection: "))
# Getting account object
for acc in accounts:
# Comparing account id
if acc.getId() == id:
accountObj = acc
break
# View Balance
if selection == 1:
# Printing balance
print(accountObj.getBalance())
# Withdraw
elif selection == 2:
# Reading amount
amt = float(input("\nEnter amount to withdraw: "))
ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ")
if ver_withdraw == "Yes":
print("Verify withdraw")
else:
break
if amt < accountObj.getBalance():
# Calling withdraw method
accountObj.withdraw(amt)
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalance()) + " n")
print("\nPlease make a deposit.");
# Deposit
elif selection == 3:
# Reading amount
amt = float(input("\nEnter amount to deposit: "))
ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ")
if ver_deposit == "Yes":
# Calling deposit method
accountObj.deposit(amt);
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
break
elif selection == 4:
print("nTransaction is now complete.")
print("Transaction number: ", random.randint(10000, 1000000))
print("Current Interest Rate: ", accountObj.annualInterestRate)
print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12)
print("Thanks for choosing us as your bank")
exit()
# Any other choice
else:
print("That's an invalid choice.")
# Main function
main()

Categories