I am trying to add exception handling to the cost and company variables.
I need an exception to make sure my cost variable is greater than $0.
And an exception on the company variable so the input is not empty. The exception on the company variable works but I am having trouble figuring out how to separate the if-else statement. I am still very new to programming.
def main():
print("This program will calculate the shipping cost based on "
"the total purchase price,\n")
while True:
try:
company = input('Please enter the company name: ')
if company == "":
raise ValueError("Please provide a valid company name.")
break
except ValueError as excpt:
print(excpt)
while True:
try:
cost = float(input("Please enter in the purchase price: "))
if cost <= 0:
raise ValueError("Please enter a value greater than $0.00.")
break
except ValueError as excpt:
print(excpt)
if cost <= 100.00:
shipping = 10.0
elif cost <= 300.00:
shipping = 8.0
elif cost <= 500.00:
shipping = 5.0
else:
shipping = 0.0
total = cost + shipping
print("At a purchase price of ${:.2f}, the shipping cost will be ${:.2f},"
" with a final total of ${:.2f}.".format(cost, shipping, total))
print('{}, thank you for shopping with us!'.format(company))
main()
This is the output:
Please enter the company name:
Please provide a valid company name.
Please enter the company name: ASX
Please enter in the purchase price: -5.99
Please enter a value greater than $0.00.
At a purchase price of $-5.99, the shipping cost will be $10.00, with a final total of $4.01.
ASX, thank you for shopping with us!
Please enter in the purchase price:
You need to fix your second indentation after the second while loop. You are breaking into emptiness.
newcode
def main():
print("This program will calculate the shipping cost based on " "the total purchase price,\n")
while True:
try:
company = input('Please enter the company name: ')
if company == "":
raise ValueError("Please provide a valid company name.")
break
except ValueError as excpt:
print(excpt)
while True:
try:
cost = float(input("Please enter in the purchase price: "))
if cost <= 0:
raise ValueError("Please enter a value greater than $0.00.")
break
except ValueError as excpt:
print(excpt)
if cost <= 100.00:
shipping = 10.0
elif cost <= 300.00:
shipping = 8.0
elif cost <= 500.00:
shipping = 5.0
else:
shipping = 0.0
total = cost + shipping
print("At a purchase price of ${:.2f}, the shipping cost will be ${:.2f},"
" with a final total of ${:.2f}.".format(cost, shipping, total))
print('{}, thank you for shopping with us!'.format(company))
if __name__ == '__main__':
main()
output
This program will calculate the shipping cost based on the total purchase price,
Please enter the company name: apple
Please enter in the purchase price: -100
Please enter a value greater than $0.00.
Please enter in the purchase price: 100
At a purchase price of $100.00, the shipping cost will be $10.00, with a final total of $110.00.
apple, thank you for shopping with us!
use assert statement instead then catch AssertionError instead of ValueError, here is how it will look like:
try:
cost = float(input())
assert cost > 0, "Cost must be greater than 0"
except AssertionError as e:
print(e)
and do the same with other inputs
Solution
# error handling made by yourself
class NoCompanyName(Exception):
pass
class CostError(Exception):
pass
# new code
def main_new():
from time import sleep
print("This program will calculate the shipping cost based on \" the totalprice\"\n")
while True:
company = input("Please enter company name.\n")
if company == None:
raise NoCompanyName("Please enter company name!")
else:
pass
while True:
cost = int(input("Please enter purchase price."))
if cost == None:
raise CostError("You should specify cost that wasn\'t lower than 0 or None!")
else:
if cost <= 0:
raise CostError("You should specify cost that wasn\'t lower than 0!")
else:
pass
if cost <= 100.00:
shipping = 10.0
elif cost <= 300.00:
shipping = 8.0
elif cost <= 500.00:
shipping = 5.0
else:
shipping = 0.0
total = cost + shipping
print(f"At purchase price of ${cost}, the shipping will cost ${shipping}. With final total is ${total}")
print(f"{company}, Thank you for shipping with us!")
sleep(5)
main_new()
Related
this is the code
wallet = int(input("wallet = "))
price = 100
print("price = " + str(price))
while price <= 1000:
if wallet >= price:
ask = input('would you like to purchase again? (y/n)')
if ask.upper() == "Y":
left = int(wallet) - price
wallet = left
print("you now have " + str(left) + " left")
elif ask.upper() == "N":
print("transaction cancelled")
else:
print("invalid reply")
left = wallet
price += 100
print('new price = ' + str(price))
else:
print("you do not have enough money to purchase more")
exit()
and this is the output
wallet = 1000
price = 100
would you like to purchase again? (y/n)y
you now have 900 left
new price = 200
would you like to purchase again? (y/n)y
you now have 700 left
new price = 300
would you like to purchase again? (y/n)y
you now have 400 left
new price = 400
would you like to purchase again? (y/n)y
you now have 0 left
new price = 500
new price = 600
new price = 700
new price = 800
new price = 900
new price = 1000
new price = 1100
you do not have enough money to purchase more
Process finished with exit code 0
i am making a continous purchase command where everytime a purchase is made, the price increase by 100, until no more money is left in customer's wallet. after which it should end but it first keeps incresing price for some time then stops.
You should stop when you have not enough money
while wallet >= price:
Also here's a better code, with removed useless conversion to int/str, and useless left that is always equals to wallet when used
wallet = int(input("wallet = "))
price = 100
print("price =", price)
while and wallet >= price:
ask = input('would you like to purchase again? (y/n)').upper()
if ask == "Y":
wallet -= price
print("you now have", wallet, "left")
elif ask == "N":
print("transaction cancelled")
else:
print("invalid reply")
price += 100
print('new price =', price)
else:
print("you do not have enough money to purchase more")
exit()
I'm trying to get Python to print every user input on a while loop. Essentially the user enters a value, then is asked again and again for a value until user decides to stop entering values. The code prints the sum of the values but also each individual value inputted.
I managed to get everything working except printing each individual value. Any help is really appreciated!
another = True
init_bal = 1000
deposit = 0
while another:
another += 1
deposit += int(input("Enter amount: "))
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
break
another = True
init_bal = 1000
deposit = 0
toatl_deposits = []
while another:
another += 1
deposit += int(input("Enter amount: "))
toatl_deposits.append(deposit)
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
print('following are list of user inputs: ')
for i in toatl_deposits:
print(f'${i}')
break
Try this,
from datetime import datetime
init_bal = 1000
deposit = 0
transactions = []
while True:
deposit += int(input("Enter amount: "))
print(f'${deposit} deposited!')
transactions.append({'time': datetime.now(), 'amount': deposit})
try:
another = int(input("Make another deposit (Yes=1, No=any)?"))
except:
break
if another != 1:
break
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print('Your transactions history:')
for transaction in transactions:
print('Deposited $' + str(transaction['amount']) + ' at ' + str(transaction['time']))
print(f'Your final balance is ${init_bal + deposit}.')
If you write this code by yourself you could understand to easily break it down and print out like this.
another = True
init_bal = 1000
deposit = 0
while another:
another += 1
amount = input("Enter amount: ")
deposit += int(amount)
print("Deposit Amount = " , amount)
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
break
The calculator does not recognize the price input being 60 as the first if statement, it will send you to else.
while True:
price = float(input("How much does it cost? (include cents!): $"))
discount=float(price)*100 / 1000
discount2=float(price)*200 /1000
proceed = 60
proceed2 = 120
if price >= proceed << proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
if price >= proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
else:
print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
I fixed it, the first if statement used << when it should have used <.
while True:
price = float(input("How much does it cost? (include cents!): $"))
discount=float(price)*100 / 1000
discount2=float(price)*200 /1000
proceed = 60
proceed2 = 120
if price >= proceed < proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
if price >= proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
else:
print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
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()
How can i print out float if the result have decimal or print out integer if the result have no decimal?
c = input("Enter the total cost of purchase: ")
bank = raw_input("Enter the bank of your credit card (DBS, OCBC, etc.): ")
dbs1 = ((c/float(100))*10)
dbs2 = c-dbs1
ocbc1 = ((c/float(100))*15)
ocbc2 = c-ocbc1
if (c > 200):
if (bank == 'DBS'):
print('Please pay $'+str(dbs2))
elif (bank == 'OCBC'):
print('Please pay $'+str(ocbc2))
else:
print('Please pay $'+str(c))
else:
print('Please pay $'+str(c))
exit = raw_input("Enter to exit")
Example-Result
Enter the total cost of purchase: 250
Enter the bank of your credit card (DBS, OCBC, etc.): OCBC
Please pay $212.5
Enter the total cost of purchase: 250
Enter the bank of your credit card (DBS, OCBC, etc.): DBS
Please pay $225.0
You can try this, which simply uses Python's string formatting method:
if int(c) == float(c):
decimals = 0
else:
decimals = 2 # Assumes 2 decimal places for money
print('Please pay: ${0:.{1}f}'.format(c, decimals))
This will give you the following output if c == 1.00:
Please pay: $1
Or this output if c == 20.56:
Please pay: $20.56
Python floats have a built-in method to determine whether they're an integer:
x = 212.50
y = 212.0
f = lambda x: int(x) if x.is_integer() else x
print(x, f(x), y, f(y), sep='\t')
>> 212.5 212.5 212.0 212
Since there is a much simpler way now and this post is the first result, people should now about it:
print(f"{3.0:g}") # 3
print(f"{3.14:g}") # 3.14
def nice_print(i):
print '%.2f' % i if i - int(i) != 0 else '%d' % i
nice_print(44)
44
nice_print(44.345)
44.34
in Your code:
def nice_number(i):
return '%.2f' % i if i - int(i) != 0 else '%d' % i
c = input("Enter the total cost of purchase: ")
bank = raw_input("Enter the bank of your credit card (DBS, OCBC, etc.): ")
dbs1 = ((c/float(100))*10)
dbs2 = c-dbs1
ocbc1 = ((c/float(100))*15)
ocbc2 = c-ocbc1
if (c > 200):
if (bank == 'DBS'):
print('Please pay $'+nice_number(dbs2))
elif (bank == 'OCBC'):
print('Please pay $'+nice_number(ocbc2))
else:
print('Please pay $'+nice_number(c))
else:
print('Please pay $'+nice_number(c))