PYTHON very BEGINNERS I need help with fixing my code, especially the \"try/exce
ID: 3791999 • Letter: P
Question
PYTHON very BEGINNERS
I need help with fixing my code, especially the "try/except" part. Thank you.
Here is the desired output:
*Part 1
*Part 2
Here is my code:
from random import *
def getPrice (price):
#price = round (uniform(0, 100), 2)
print ("The price is: $" +str (price))
return float(price)
def calcPayment ():
price= getPrice(55.77)
#price= getPrice(87.33)
payment = float(input("Enter your payment:"))
change= payment-price
dues= price-payment
if payment >= price:
print ("Here's your change of $" + str(round (change, 2)))
elif payment < 0:
print ("Payment must be a positive value larger than price")
elif payment < price:
print ("That's not enough. You need $" + str(round(dues, 2))+" more")
# exception handling:
# payment is a string (non-numeric value)
return payment
try:
payment = ????????????
except: # could not convert string to float
print ("You must enter a numeric value")
calcPayment ()
Payment okay: The price is $52.75 Enter your payment 60 Here's your change of $7.25 Payment too sma The price is: $87.33 Enter your payment 50 That's not enough. You need $37.33 moreExplanation / Answer
from random import *
def getPrice (price):
#price = round (uniform(0, 100), 2)
print ("The price is: $" +str (price))
return float(price)
def calcPayment ():
price= getPrice(55.77)
#price= getPrice(87.33)
try:
payment = float(input("Enter your payment:"))
except:
print ("You must enter a numeric value")
return
change= payment-price
dues= price-payment
if payment >= price:
print ("Here's your change of $" + str(round (change, 2)))
elif payment < 0:
print ("Payment must be a positive value larger than price")
elif payment < price:
print ("That's not enough. You need $" + str(round(dues, 2))+" more")
return payment
calcPayment ()
here are sample runs
sh-4.3$ python main.py
The price is: $55.77
Enter your payment:60
Here's your change of $4.23
sh-4.3$ python main.py
The price is: $55.77
Enter your payment:40
That's not enough. You need $15.77 more
sh-4.3$ python main.py
The price is: $55.77
Enter your payment:thirty dollar
You must enter a numeric value
sh-4.3$ python main.py
The price is: $55.77
Enter your payment:-10
Payment must be a positive value larger than price
sh-4.3$ python main.py
The price is: $55.77
Enter your payment:55.77
Here's your change of $0.0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.