I am writing a code in python where I use different functions to calculate wage, federal tax, state tax, and net worth. Everything is fine except my output says, ('Your wage is: $', 989) instead of Your wage is: $989 I tried using +(wag) but it doesn't let me run it. How do I get rid of the parenthesis, comma, and quotation marks from the output? And how do I make the output have no decimal points? I am not using float, so I don't know why it's still giving me decimal points. Here's my code:
def Calculatewages():
wage = (work*hours)
return wage
def CalcualteFederaltax():
if (status== ("Married")):
federaltax = 0.20
elif (status== ("Single")):
federaltax = 0.25
elif status:
federaltax = 0.22
federaltax = float(wag*federaltax)
return federaltax
def Calculatestatetax():
if(state=="CA") or (state=="NV") or (state=="SD") or (state=="WA") or (state=="AZ"):
statetax = 0.08
if (state== "TX") or(state=="IL") or (state=="MO") or (state=="OH") or (state=="VA"):
statetax = 0.07
if (state== "NM") or (state== "OR") or (state=="IN"):
statetax = 0.06
if (state):
statetax = 0.05
statetax = float(wag*statetax)
return statetax
def Calculatenet():
net = float(wag-FederalTax-StateTax)
return net
hours = input("Please enter your work hours: ")
work = input("Please enter your hourly rate: ")
state = input("Please enter your state of resident: ")
status = input("Please enter your marital status: ")
print("**********")
wag = Calculatewages()
FederalTax = CalcualteFederaltax()
StateTax = Calculatestatetax()
Net = Calculatenet()
print("Your wage is: $" ,wag)
print("Your federal tax is: $",FederalTax)
print("Your state tax is: $",StateTax)
print("Your net wage is: $",Net)
For this part:
print("Your wage is: $" ,wag)
print("Your federal tax is: $",FederalTax)
print("Your state tax is: $",StateTax)
print("Your net wage is: $",Net)
you can rewrite it as this using string's format() method:
print("Your wage is: ${}".format(wag))
print("Your federal tax is: ${}".format(FederalTax))
print("Your state tax is: ${}".format(StateTax))
print("Your net wage is: ${}".format(Net))
This is useful as you can insert the value into any place in the string (wherever you put the curly brackets).
As for your decimal points problem you can use the built in round function like this:
round(float(variable), int(decimal_places))
for example:
round(1.43523556, 2)
will return 1.44
There are no quotes or parenthesis in the output in python 3.x, Check if you are running on python 2 or python 3. Looks like you are on python 2 by judging your output.
So change all your print statements like this
print "Your net wage is: $", wag # remove brackets
...
However, if you want it to run on python 3 your code doesn't run as you are multiplying 2 strings in this line
def Calculatewages():
wage = (work*hours) # <------ here
return wage
To fix this issue you must cast them into int and then your code should run without problems.
hours = int(input("Please enter your work hours: ")) # < ---- Cast to int
work = int(input("Please enter your hourly rate: ")) # < ---- Cast to int
state = input("Please enter your state of resident: ")
status = input("Please enter your marital status: ")
My output:
Please enter your work hours: 8
Please enter your hourly rate: 10
Please enter your state of resident: IN
Please enter your marital status: Single
**********
Your wage is: $ 80
Your federal tax is: $ 20.0
Your state tax is: $ 4.0
Your net wage is: $ 56.0
you can also use string's format() method:
print("Your wage is: ${}".format(wag))
print("Your federal tax is: ${}".format(FederalTax))
print("Your state tax is: ${}".format(StateTax))
print("Your net wage is: ${}".format(Net))
If you're running under python3.x, then with your code, it should print out without the parenthesis, and if you're running under python2.x, then to get rid of the parenthesis, you might wanna try:
print "Your wage is: $", wag
Related
I am brand new to coding so I hope this is a small mistake. Below is the code for an assignment on a paper carrier's salary. I get no error codes but no output, even the print functions do not show. Please help
# This program will calculate the weekly pay of a paper carrier.
# Developer: Hannah Ploeger Date: 08/30/2022
def main():
# initialize variables
paperCost = 4
commission = 0.05
# prompt user for number of papers
numPaper = eval(input("How many papers are delivered on your route?"))
# prompt user for days of delivery
numDays = eval(input("How many days was the paper delivered this week"))
# prompt user for tips recieved
numTips = input("How much did you recieve in tips this week?")
# calculate salary
weekPay = ((numPaper * numDays) * paperCost) * commission
totalPay = weekPay + numTips
# display output
print("This week you delivered", numPaper, "papers")
print("Your salary this week is $", weekPay)
print("Your total tips were $", numTips)
print("Your total pay is $", totalPay)
enter image description here
add this:
if __name__ == "__main__":
main()
just call the main function
def main():
# initialize variables
paperCost = 4
commission = 0.05
# prompt user for number of papers
numPaper = eval(input("How many papers are delivered on your route?"))
# prompt user for days of delivery
numDays = eval(input("How many days was the paper delivered this week"))
# prompt user for tips recieved
numTips = input("How much did you recieve in tips this week?")
# calculate salary
weekPay = ((numPaper * numDays) * paperCost) * commission
totalPay = weekPay + numTips
# display output
print("This week you delivered", numPaper, "papers")
print("Your salary this week is $", weekPay)
print("Your total tips were $", numTips)
print("Your total pay is $", totalPay)
main() # calling main function
I am trying to create a program that inputs the price and tax rate and returns the item number, price, tax rate, and item price in an orderly format.
Here is the criteria:
The user can enter multiple items until the user says otherwise.
It calculates and display the total amount of purchased items on the bottom.
The price gets a 3% discount if the total amount is 1000 or more
I am not allowed to use arrays to solve this problem and I must separate the inputs from the outputs on the screen.
An example output is shown here:
Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n) y
Enter the price: 34
Enter the tax rate: 10
Are there any more items? (y/n) y
Enter the price: 105.45
Enter the tax rate: 7
Are there any more items? (y/n) n
Item Price Tax Rate % Item Price
====================================
1 245.78 12% 275.27
2 34.00 10% 37.40
3 105.45 7% 112.83
Total amount: $425.51
Here is my code so far:
price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc= 0
while True:
query=input('Are there any more items? (y/n)')
if query== 'y':
price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
print(itemPrice )
acc+=1
elif query=='n':
break
print ("Item Price Tax Rate% Item Price")
print ("=========================================")
print( (acc+1) , format(price,'10.2f'), format(taxRate,'10.2f') ,
format(itemPrice,'14.2f') )
for num in range(0,acc):
print (acc, price, taxRate, itemPrice)
The output is shown as this:
Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n)y
Enter the price: 34
Enter the tax rate: 10
37.400000000000006
Are there any more items? (y/n)y
Enter the price: 105.45
Enter the tax rate: 7
112.8315
Are there any more items? (y/n)n
Item Price Tax Rate% Item Price
=========================================
3 105.45 7.00 112.83
2 105.45 7.0 112.8315
2 105.45 7.0 112.8315
I just have a hard time trying to do this without using an array.. can anyone be of assistance?
You could build a string as a buffer for the output?
Like this:
out = ""
acc = 0
totalAmount = 0
query = 'y'
while query == 'y':
price = float(input('Enter the price: '))
taxRate = float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc += 1
totalAmount += itemPrice
out += f"{acc:>4} {price:9.2f} {taxRate:11.2f}% {itemPrice:13.2f}\n"
query = input('Are there any more items? (y/n) ')
print("Item Price Tax Rate% Item Price")
print("=========================================")
print(out)
print(f"Total amount: ${totalAmount:.2f}")
if totalAmount >= 1000:
print(" Discount: 3%")
print(f"Total amount: ${totalAmount*0.97:.2f} (after discount)")
here is the code=
def main():
print("Enter your age: ")
age= float(input())
while age >= 0:
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
and here is the problem I am trying to solve:
Create a program that begins by reading the ages of all of the guests in a group from the user, with one age entered on each line. The user will enter -1 to indicate that there are no more guests in the group. Then your program should display the admission cost for the group with an appropriate message. The cost should be displayed using two decimal places. Use the following sample run for input and output messages.
You need to move the prompt for input into the loop, otherwise age never changes within the while, creating an infinite loop.
def main():
age = 1
while age >= 0:
print("Enter your age: ")
age = float(input())
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
You never update age after its initial value and so the while loop continues forever, printing a line for each iteration.
You need to put a
age = float(input())
as the last line of the while loop.
#Program to calculate cost of gas on a trip
#Created by Sylvia McCoy, March 31, 2015
#Created in Python
#Declare Variables
Trip_Destination = 0
Number_Miles = 0
Current_MPG = 0.0
Gallon_Cost = 0.0
Total_Gallons = 0.0
Total_Cost = 0.0
#Loop to enter destinations
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = float(input("Enter how many miles to your destination: "))
Gallon_Cost = float(input("Enter how much a gallon of gas costs: "))
Current_MPG = float(Number_Miles / Gallon_Cost)
print("Your trip to: " + Trip_Destination)
print("Your total miles: " + Number_Miles)
print("Your MPG: " + Current_MPG)
Error in line 20 and 21...stated earlier as float, how do I get them to print? Have to do the work in Python. Thanks!
You can't use the + operator to combine a string with a float.
It can only be used to combine two of a single type (eg.2 strings, 2 floats, etc.)
With that said, to get your desired output, you can simplify ALL the conversions you need into one line, like so:
Trip_Destination = 0
Number_Miles = 0
Current_MPG = 0.0
Gallon_Cost = 0.0
Total_Gallons = 0.0
Total_Cost = 0.0
#Loop to enter destinations
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = input("Enter how many miles to your destination: ")
Gallon_Cost = input("Enter how much a gallon of gas costs: ")
Current_MPG = str(float(Number_Miles) / float(Gallon_Cost))
print("Your trip to: " + Trip_Destination)
print("Your total miles: " + Number_Miles)
print("Your MPG: " + Current_MPG)
Using the input() function by itself will let you get a value from the user (already in the form of a string). This way, you won't have to format/convert it later.
Check this out
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = float(input("Enter how many miles to your destination: "))
Gallon_Cost = float(input("Enter how much a gallon of gas costs: "))
Current_MPG = float(Number_Miles / Gallon_Cost)
print("Your trip to: " + Trip_Destination)
print("Your total miles:{}".format(Number_Miles))
print("Your MPG:{}".format(Current_MPG))
print("your string {}".format(x))
its called string formatting
Concatenation
You are trying to add a string and a float, in Python the two won't be automatically casted.
print("Your total miles: " + str(Number_Miles)) # same for miles per gallon
String Formats
Otherwise, you can also use string formatting in order to interpolate the desired variable.
print("Your total miles: {0}".format(Number_Miles)) # same miles per gallon
subtotal = input("What's the Subtotal?") #input of dinners subtotal
tax_input = input("What's the tax there?") #local tax
tip_input = .20 #average tax is 20%
tax = subtotal * tax_input #tax
tip = subtotal * tip_input #tip
total = subtotal + tax + tip #totalling
print "Your %s was " + tax (tax)
print "Your %s was " + tip (tip)
print "Your %s is " + total (total)
What does the error "TypeError: 'undefined' object is not callable" mean? Also, is my code good? I know that instead of using two tax's I can just change the value, but that seems weird to me...
Did you want to do something like that?
subtotal = input("What's the Subtotal?") #input of dinners subtotal
tax_input = input("What's the tax there?") #local tax
tip_input = .20 #average tax is 20%
tax = subtotal * tax_input #tax
tip = subtotal * tip_input #tip
total = subtotal + tax + tip #totalling
print "Your tax was %s" %tax
print "Your tip was %s" %tip
print "Your total is %s" %total
The problem in your code is this
print "Your %s was " + tax (tax)
tax is not a method so you can't call it. Your tax is either int or float, so you need to make it a string to concatenate, either by doing this
print "Your tax was %s" %tax
or
print "Your tax was " + str(tax)
Changing your prints as follows should help:
print("Your tax was {} ".format(tax))
print("Your tip was {}".format(tip))
print("Your total is {}".format(total))
Your code does not work, because tax, tip and total are not functions or callable objects. They just numbers.
You are trying to call tax, tip and total as if they were functions. They are variables, and not functions. If you want to replace the strings tax, tip, and total with their respective "titles" you would need to take an approach that uses iterate-able key/value hash (which python conveniently makes easy, but that's for another discussion).
Instead you could simply do something like:
`
print "Your tax was", tax
print "Your tip was", tip
print "Your total was", total
`
The truth is your code sucks. So does mine. It will probably always suck. Get used to regularly looking back on code you've written before and hating yourself for writing such horrible, wretched code in the first place.