Home > OS >  Any way to make my code shorter to perhaps to 2 variebles while still keeping it to 2 decimals?
Any way to make my code shorter to perhaps to 2 variebles while still keeping it to 2 decimals?

Time:12-11

Trying to make my code shorter just a few points away from #1.

I tried shrinking it but its just too complicated.

Taxers = int(input("Will you be eating in 1 For Yes 2 For No:"))
TotalCostA = TotalCostB * 0.05
Tax = TotalCostA
TotalCostF = "{:.2f}".format(Tax)
TotalCostT = Tax   TotalCostB
if Taxers == 2:
    print("Tax = 0")
    print("Your total pizza cost it", TotalCostB, "kd")
else:
    print("Tax = ", TotalCostF)
    print("Your total pizza cost it", TotalCostT, "kd")

CodePudding user response:

You can get rid of the extra variables and use f-strings for a slightly more fluent experience:

Taxers = int(input("Will you be eating in 1 For Yes 2 For No:"))
TotalCostA = TotalCostB * 0.05
TotalCostT = TotalCostA   TotalCostB
if Taxers == 2:
    print("Tax = 0")
    print(f"Your total pizza cost it {TotalCostB} kd")
else:
    print(f"Tax = {TotalCostA:.2f}")
    print(f"Your total pizza cost it {TotalCostT} kd")

Shortening it even further will reduce code readability. On that note, I strongly recommend you to follow the Python naming conventions and improve the variable names to something more descriptive, e.g. cost_with_tax.

CodePudding user response:

Assuming you can't change the text printed while taking input and returning output, here is my attempt. I think you have not defined TotalCostB, so change accordingly.

print(["Tax = 0" "\nYour total pizza cost it " str(TotalCostB) " kd","Tax = " "{:.2f}".format(TotalCostB * 0.05) "\nYour total pizza cost it " "{:.2f}".format(TotalCostB * 1.05) " kd"][int(input("Will you be eating in 1 For Yes 2 For No:")) == 2])

CodePudding user response:

You need to think about making your code more robust (which involves more code) then you can start thinking about simplification.

Consider this:

tax = {1: 0.05, 2: 0.00}
pizzacost = 4.00
while True:
    userinput = input('Will you be eating in 1 For Yes 2 For No: ')
    try:
        if (inorout := int(userinput)) in tax:
            break
    except ValueError:
        pass
print(f'Tax = {tax[inorout] * pizzacost:.2f}kd\nYour total pizza cost is {pizzacost * (1   tax[inorout]):.2f}kd')
  • Related