Aligning Separate Parts of Print - python

I am trying to align the text in my output.
purch_amt = float(input('Enter Amount of Purchase'))
state_stax = purch_amt * 0.04
county_stax = purch_amt * 0.02
tax = state_stax + county_stax
totalprice = purch_amt + tax
Print("Purchase Price", "= $", %.2f % purch_amt)
Print("State Sales tax", "= $", %.2f % state_stax)
Print("County Sales tax", "= $", %.2f % county_stax)
Print("Total Tax", "= $", %.2f % tax)
Print("Total Price", "= $", %.2f % totalprice)
... and I want it to look like this when it is run.
Purchase Price = $ 100.00
State Sales tax = $ 4.00
County Sales tax = $ 2.00
Total Tax = $ 6.00
Total Price = $ 106.00
The only way I've found to do this is extremely complex for something that should be fairly easy.
Problem solved, Thanks!
purch_amt = float(input('Enter Amount of Purchase'))
state_stax = purch_amt * 0.04
county_stax = purch_amt * 0.02
tax = state_stax + county_stax
totalprice = purch_amt + tax
def justified(title, amount, titlewidth=20, amountwidth=10):
return title.ljust(titlewidth) + " = $ " + ('%.2f' % amount).rjust(amountwidth)
print(justified('Purchase Price', purch_amt))
print(justified('State Sales Tax', state_stax))
print(justified('County Sales Tax', county_stax))
print(justified('Total Tax', tax))
print(justified('Total Price', totalprice))

String ljust, rjust, center are what you want for padding a string like that.
def justified(title, amount, titlewidth=20, amountwidth=10):
return title.ljust(titlewidth) + " = $ " + ('%.2f' % amount).rjust(amountwidth)
print(justified('Parts', 12.45))
print(justified('Labor', 100))
print(justified('Tax', 2.5))
print(justified('Total', 114.95))

You can just use the built-in string formatting:
>>> column_format = "{item:20} = $ {price:>10.2f}"
>>> print(column_format.format(item="Total Tax", price=6))
Total Tax = $ 6.00
...etc.
Breaking this down:
{item} means format the parameter named item
{item:20} means the formatted result should have width 20 characters
{price:>10.2f} means right align (>), width of 10 (10), floating point precision of 2 decimal places (.2f)
Incidentally, you might want to look at the Decimal package for currency work.

Related

New to python and having trouble figuring out why the deductions are not including the tax in the total

I am new to programming and I am trying to write a program for the python essentials course I am in. It's on Day 1 and I am having trouble figuring out why the Total Deductions will not compute the correct amount. This is the code I wrote:
print("=================DEDUCTIONS=================")
print("SSS: " + sss_contribution)
print("PhilHealth: " + philhealth_contribution)
print("Other Loan: " + housing_loan)
tax_rate = .10
tax_total = int(gross_salary)*int(tax_rate)
print("Tax: " + str(tax_total))
total_deductions = int(sss_contribution) + int(philhealth_contribution) + int(housing_loan) + int(tax_total)
print("Total Deductions: " + str(total_deductions))
net_salary = float(gross_salary) - float(total_deductions)
print("NET SALARY: " + str(net_salary))
I get the correct NET SALARY amount, but the Total Deductions only reflect the total for the SSS, PhilHealth, and Housing. Thank you.
You declared tax_rate as a float, so try:
tax_total = int(gross_salary)*float(tax_rate)
If you declared tax_rate as 5.10, doing an int(tax_rate) returns 5. Wheras doing a float(tax_rate) returns 5.1.
Here in your example you declared tax_rate as 0.10, so your tax_total becomes 0 since int(tax_rate) is 0. Thats why your tax is not included in your calculations
print("=================DEDUCTIONS=================")
sss_contribution = 500
philhealth_contribution = 600
housing_loan = 500.20
gross_salary = 2000
print("SSS: " +str(sss_contribution))
print("PhilHealth: " +str(philhealth_contribution))
print("Other Loan: " +str(housing_loan))
tax_rate = .10
tax_total = int(gross_salary)*float(tax_rate)
print("Tax: " + str(tax_total))
total_deductions = int(sss_contribution) + int(philhealth_contribution) + float(housing_loan) + int(tax_total)
print("Total Deductions: " + str(total_deductions))
net_salary = float(gross_salary) - float(total_deductions)
print("NET SALARY: " + str(net_salary))

My very first python program! An income tax calculator

I am brand new to python and I attempted to make a simple federal income tax calculator. There has to be a far simpler way to accomplish the same task. Here's what I created:
'''
# 2021 income tax calculator
print ('What\'s your yearly income after you deduct all expenses?')
myincome = int(input())
base = (myincome*.1)
e = (max(myincome-9950,0)*.02)
ex = (max(myincome-40525,0)*.1)
ext = (max(myincome-86376,0)*.02)
extr = (max(myincome-164926,0)*.08)
extra = (max(myincome-209426,0)*.03)
extras = (max(myincome-523601,0)*.02)
tax = base + e + ex + ext + extr + extra + extras
print ('You\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax')
print ()
while True:
print ('Try Different Income:')
myincome = int(input())
base = (myincome*.1)
e = (max(myincome-9950,0)*.02)
ex = (max(myincome-40525,0)*.1)
ext = (max(myincome-86376,0)*.02)
extr = (max(myincome-164926,0)*.08)
extra = (max(myincome-209426,0)*.03)
extras = (max(myincome-523601,0)*.02)
tax = base + e + ex + ext + extr + extra + extras
print ('You\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax')
print ()
continue
'''
Try this code:
# create a dictionary with amounts and rates (the key is the amount, the value is the rate)
stakes = {0: .1, 9950: .02, 40525: .1, 86376: .02, 164926: .08, 209426: .03, 523601: .02}
myincome = input('What\'s your yearly income after you deduct all expenses? ')
while myincome.isnumeric(): # loop ends if entered empty or non-numeric string
myincome = int(myincome)
# a cycle in which key-value pairs (amount-rate) are alternately extracted (unpacked)
# from the dictionary, partial taxes is calculated and the result is summed up
tax = sum(max(myincome - k, 0) * v for k, v in stakes.items())
print(f'You\'re gonna get screwed about~${tax} dollars in Federal income tax')
myincome = input('Try Different Income:')

Incorrect or no user input for multiple questions

Here is a program that asks a user for string and int inputs. If someone enters the wrong type on input or no input at all, the program ends with an error. I need to handle the exceptions for every one of the questions that is asked. How do I do this? Do I only need one "while true" line? Can it be in one try block?
Thank you,
Matt
customerName = input("Customer Name:\n")
mixName = input("Mix Name:\n")
L_Citrulline_Mallate = int(input("Amount of L-Citrulline Malate (2:1) per serving(grams):\n"))
Beta_Alanine = int(input("Amount of Beta Alanine per serving(grams):\n"))
Caffeine_Anhydrous = float(input("Amount of Caffeine Anhydrous per serving(milligrams):\n"))/1000
Betaine_Anhydrous = int(input("Amount of Betaine Anhydrous per serving(grams):\n"))
Taurine = int(input("Amount of Taurine per serving(grams):\n"))
Creatine_HCL = int(input("Amount of Creatine_HCL per serving(grams):\n"))
L_Theanine = float(input("Amount of L-Theanine per serving(milligrams):\n"))/1000
L_Tyrosine = int(input("Amount of L-Tyrosine per serving(grams):\n"))
Sodium_Bicarbonate = float(input("Amount of Sodium_Bicarbonate per serving(milligrams):\n"))/1000
servings = 35
#Mix Total
Mix_Total = float(L_Citrulline_Mallate + Beta_Alanine + Caffeine_Anhydrous + Betaine_Anhydrous + Taurine + Creatine_HCL + L_Theanine + L_Tyrosine + Sodium_Bicarbonate)* servings
#Servings Total
Serving_Total = float(L_Citrulline_Mallate + Beta_Alanine + Caffeine_Anhydrous + Betaine_Anhydrous + Taurine + Creatine_HCL + L_Theanine + L_Tyrosine + Sodium_Bicarbonate)
Flavor_Weight = float(Serving_Total*.25)
Flavor_Weight_Total = float(Flavor_Weight * servings)
Grand_Serving_Total_Weight = float(Flavor_Weight + Serving_Total)
Grand_Weight_Mix_Total = float(Grand_Serving_Total_Weight * servings)
#while
while (Grand_Weight_Mix_Total > 450):
servings = servings - 1
Grand_Weight_Mix_Total = float(Grand_Serving_Total_Weight * servings)
print('Servings loop value', servings)
#Flavor weight total calc
Flavor_Weight_Total = float(Flavor_Weight * servings)
#Print
print (f'Customer: {customerName}')
print (f'Mix Name: {mixName}')
print (f'Servings: {servings}')
print (f'L-Citrulline Malate: {L_Citrulline_Mallate}')
print (f'Beta Alanine: {Beta_Alanine}')
print (f'Caffeine Anhydrous: {Caffeine_Anhydrous}')
print (f'Betaine Anhydrous: {Betaine_Anhydrous}')
print (f'Taurine: {Taurine}')
print (f'Creatine HCL: {Creatine_HCL}')
print (f'L-Theanine: {L_Theanine}')
print (f'L-Tryosine: {L_Tyrosine}')
print (f'Sodium Bicarbonate: {Sodium_Bicarbonate}')
#Calculate total grams needed for each ingredent
Total_L_Citrulline_Mallate = int(L_Citrulline_Mallate * servings)
Total_Beta_Alanine = int(Beta_Alanine * servings)
Total_Caffeine_Anhydrous = float(Caffeine_Anhydrous * servings)
Total_Betaine_Anhydrous = int(Betaine_Anhydrous * servings)
Total_Taurine = int(Taurine * servings)
Total_Creatine_HCL = int(Creatine_HCL * servings)
Total_L_Theanine = float(L_Theanine * servings)
Total_L_Tyrosine = int(L_Tyrosine * servings)
Total_Sodium_Bicarbonate = float(Sodium_Bicarbonate * servings)
#Recalculation Grand_Weight_Total_Mix
Grand_Weight_Mix_Total = float(Grand_Serving_Total_Weight * servings)
Mix_Total = float(L_Citrulline_Mallate + Beta_Alanine + Caffeine_Anhydrous + Betaine_Anhydrous + Taurine + Creatine_HCL + L_Theanine + L_Tyrosine + Sodium_Bicarbonate)* servings
#Print total grams of each ingredient
print("L-Citrulline Mallate Total Grams:", Total_L_Citrulline_Mallate)
print("Beta Alanine Total Grams:", Total_Beta_Alanine)
print("Caffeine Anhydrous Total Grams:", Total_Caffeine_Anhydrous)
print("Betaine Anhydrous Total Grams:", Total_Betaine_Anhydrous)
print("Taurine Total Grams:", Total_Taurine)
print("Creatine HCL Total Grams:", Total_Creatine_HCL)
print("L-Theanine Total Grams:", Total_L_Theanine)
print("L-Tyrosine Total Grams:", Total_L_Tyrosine)
print("Sodium Bicarbonate Total Grams:", Total_Sodium_Bicarbonate)
print("Mix serving weight (flavor not included): ", Serving_Total)
print("Mix total weight: ", Mix_Total)
print("Flavor Serving Weight", Flavor_Weight)
print("Flavor Total Weight", Flavor_Weight_Total)
#Grand_Total_Serving_Weight variable name is printer as 'Serving Weight'
print("Serving Weight", Grand_Serving_Total_Weight)
print("Total Weight", Grand_Weight_Mix_Total)
It sounds like it would be worth you making a function which will prompt for input, convert to the desired type, and if that fails then issue a message and try again. You can then call this (instead of input directly) for each data item. Example:
def get_input(prompt, type_=str):
while True:
try:
return type_(input(prompt))
except ValueError:
print(f"Bad input - type {type_.__name__} is needed - try again")
customerName = get_input("Customer Name: ")
L_Citrulline_Mallate = get_input("Amount of L-Citrulline: ", int)
L_Theanine = get_input("Amount of L-Theanine: ", float) / 1000
print(customerName, L_Citrulline_Mallate, L_Theanine)
If you also want to reject empty string input, then you can test for this as well. For example:
def get_input(prompt, type_=str, allow_empty=False):
while True:
response = input(prompt)
if response == "" and not allow_empty:
print("You must enter something")
continue
try:
return type_(response)
except ValueError:
print("Bad input - type {} is needed - try again".format(type_.__name__))
customerName = get_input("Customer Name: ")
comment = get_input("Any comment?: ", allow_empty=True)
I am assuming that it is only for Int and Float type of input. Then this can be achieved with something like this:
try:
num1 = float(input("Enter float"))
num2 = int(input("Enter Int"))
print(num1,num2)
except ValueError:
print("Hey you have entered the wrong datatype")

How to automatically make a NoneType into a string?

This is my code:
from yahoo_finance import Share
from pprint import pprint
laz = Share('LAZ') #Lazard
# ABERDEEN
amg = Share('AMG') #Affiliated Managers Group
ben = Share('BEN') #Franklin Resources
lm = Share('LM') #Legg Mason
evr = Share('EVR') #Evercore Partners
ghl = Share('GHL') #Greenhill
hli = Share('HLI') #Houlihan Lokey
mc = Share('MC') #Moelis
pjt = Share('PJT') #PJT Partners
ms = Share('MS') #Morgan Stanley
gs = Share('GS') #Goldman Sachs
jpm = Share('JPM') #JP Morgan
ab = Share('AB') #Alliance Bernstein
print ("Lazard: $" + laz.get_open())
# ABERDEEN
print ("AMG: $" + amg.get_open())
print ("Franklin: $" + ben.get_open())
print ("LeggMason: $" + lm.get_open())
print ("Evercore: $" + evr.get_open())
print ("Greenhill: $" + ghl.get_open())
print ("Houlihan: $" + hli.get_open())
print ("Moelis: $" + mc.get_open())
print ("PJT: $" + pjt.get_open())
print ("MorganStanley: $" + ms.get_open())
print ("Goldman: $" + gs.get_open())
print ("JPMorgan: $" + jpm.get_open())
print ("AllianceBernstein: $" + ab.get_open())
This is the error I am getting:
Traceback (most recent call last):
File "C:/Users/ballz/Documents/Python/PDF to Excel/StockPerformance/stockcompetitoranalyis.py", line 26, in <module>
print ("Houlihan: $" + hli.get_open())
TypeError: must be str, not NoneType
However, it is really weird becuase it works half the time, and the other half it does not. Why do the rest work, but this specific one does not?
I think this will work..
Just use this function Share_nonesafe instead of Share
from yahoo_finance import Share
def Share_nonesafe(x):
if Share(x) == None:
return (' price not available.')
else:
return (Share(x))

Help with a python code

I'm reading this python book called "Python for software design" and it has the following exercise:
Suppose the cover price of a book is $24.95, but the bookstores get a 40% discount.
Shipping costs $3 for the first copy and 75 cents for each additional copy. What
is the total wholesale cost for 60 copies
ok, i have the following code:
bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60
bookDiscountAmount = bookPrice * discount * totalUnits
shipping = shippingPriceRest * 59 + shippingPriceFirst
result = bookDiscountAmount + shipping
print 'The total price for 60 books including shipping and discount is: '
print 'Total price of the books is: ' + str(bookDiscountAmount)
print 'Total Shipping is: ' + str(shipping)
print 'The Total price is: ' + str(result)
With that I get the following results:
The total price for 60 books including shipping and discount is:
Total price of the books is: 898.2
Total Shipping is: 47.25
The Total price is: 945.45
My questions are:
Is this correct?
How can i make this code better?
There are only three things to change:
1) You duplicated the number of books: 60 and 59 both appear in the code. You shouldn't have 59 in there.
2) Print you results like this: print 'The total price is: %.2f' % result
3) Usual Python convention is to name variables_like_this, notLikeThis.
The only improvement I would suggest is to use the format-function instead of string concatenation:
print """The total price for {0:d} books including shipping and discount is:
Total price of the books is: {1:7.2f}
Total Shipping is: {2:7.2f}
The Total price is: {3:7.2f}""".format(totalUnits, bookDiscountAmount
shipping, result)
this makes all the numbers nicely aligned and equally formatted (with two digits after the decimal-point and a total precision of 7).
Edit: And of course, as the other pointed out, don't hard-code the 59 there.
It looks right to me. I would avoid hard-coding 59. Instead, check whether the total is more than one, and divide up as appropriate.
Also, this is minor, but bookDiscountAmount should be bookDiscountedAmount (the discount is the amount they save, not the amount they pay). Other people have pointed out how to improve the string printing.
i did it this way but i still believe that with a function as above would be better
price = 24.95
discount = price * (40/100)
d_price = price - discount
shipping = 3 + (0.75 * (60 - 1))
wholesale = d_price * 60 + shipping
Please try this:
bookCost = 24.95
numBooks = 60.0
def cost(numBooks):
bulkBookCost = ((bookCost * 0.60) * numBooks)
shippingCost = (3.0 + (0.75 * (numBooks - 1)))
totalCost = bulkBookCost + shippingCost
print 'The total cost is: $', totalCost
cost(numBooks)
'''Suppose the cover price of a book is $24.95, but bookstores get a 40%
discount. Shipping costs $3 for the first copy and 75 cents for each
additional copy. What is the total wholesale cost for
60 copies?
'''
import math
book_price = float(24.95)
discount = float(book_price * 40 /100)
Book_Price= float(book_price - discount)
print ('Book Price is without shipping charges = ' , Book_Price)
shipping = 3.0
Total_Price = float(Book_Price + shipping)
print ('The book 1st price is =' ,Total_Price)
Quantity = int(input('Enter the Number of Copies = '))
if Quantity > 1:
Price = float(Book_Price * Quantity)
Additional_copy_price = 0.75
Q = float(Quantity * Additional_copy_price)
Final_Price = float(Price + Q + 3 - .75)
print (' Final price for more than one copy is = ' , Final_Price)
else:
print (Total_Price)
cov_price = 24.95 #cost of one book
discount = 0.4
per_one = (cov_price-(cov_price*discount)) #cost of one book on discount
ship_cost = 3 #shipment on first book
other_ship = 0.75 #shipment on other books
purchased = input("Enter number of books purchased : ")
purchased = int(purchased)
if(purchased):
cost = ((other_ship*(purchased-1)+(per_one*(purchased-1))) + (per_one+3))
print("The cost of books purchased including discount = ",cost)
print("Price per one is =",per_one)
i'm a beginner to python and this worked fine for me
bc = 24.95 #book cost real price
dis = 0.40 # discount percent
bcd = bc*dis # discount amount
bp = bc - bcd # book price
scf = 3 # shipping cost for the first book
scr = 0.75 # shipping cost for the rest books
cost1 = bp*scf
cost2 = bp*scr*59
TotalCost = cost1 + cost2
print(TotalCost)
This is my basic solution to this problem
price = 24.95 - (24.95)*4/10
order = 60
shipping = 3 + 0.75*(order-1)
print('The total price for 60 books including shipping and discount is %.2f$' % (order*price + shipping))
n = int(input('Enter the number of copies : '))
Book_store_price_of_one_copy = (60*24.95)/100
Shipping_cost_for_copy = (3+((n-1)*0.75))
whole_sale = (n*Book_store_price_of_one_copy)+Shipping_cost_for_copy
print(f'Whole sale of {n} copies is {whole_sale}')
#######################################################################################
#Your code, commented
#######################################################################################
bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60
bookDiscountAmount = bookPrice * discount * totalUnits # Poor variable name choice. This is not the book discount amount, it's the cost of all books without shipping
shipping = shippingPriceRest * 59 + shippingPriceFirst # You should really use your variables as much as possible. Instead of 59, use totalUnits - 1
result = bookDiscountAmount + shipping
print 'The total price for 60 books including shipping and discount is: '
print 'Total price of the books is: ' + str(bookDiscountAmount)
print 'Total Shipping is: ' + str(shipping)
print 'The Total price is: ' + str(result)
#######################################################################################
#An example of your code, cleaned up
#######################################################################################
bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60
totalCostBeforeShipping = (bookPrice * discount) * totalUnits
shipping = (shippingPriceRest * (totalUnits-1)) + shippingPriceFirst
result = totalCostBeforeShipping + shipping
print 'The total price for 60 books including shipping and discount is: '
print 'Total price of the books is: ' + str(totalCostBeforeShipping)
print 'Total Shipping is: ' + str(shipping)
print 'The Total price is: ' + str(result)
#######################################################################################
#An example of another method, using a loop
#######################################################################################
bookPrice = 24.95
discount = 40 # %
bookPriceWithDiscount = bookPrice * ((100.0-discount)/100.0)
firstBookShippingPrice = 3
otherBookShippingPrice = .75
totalBooks = 60
totalCost = 0
for book in range(totalBooks):
if book == 0:
totalCost += firstBookShippingPrice
else:
totalCost += otherBookShippingPrice
totalCost += bookPriceWithDiscount
shipping = firstBookShippingPrice + (otherBookShippingPrice * totalBooks)
print 'The total price for 60 books including shipping and discount is:'
print 'Total price per book is: %d'%(bookPriceWithDiscount)
print 'Total shipping is: %d'%(shipping)
print 'The total price is: %d'%(result)

Categories