I would like to make sure input from the user is in $XX or $XX.XX format. If it's in $XX then the program would change the $XX to $XX.00. Basically I want to get an amount in dollars and cents from the user, make sure that it is a float with decimal (if not, return an error message and ask for input again) and then confirm the amount is correct with the user. I'm just starting out so multiple techniques are welcome and an explanation on which would be best. Thank you in advance!!!
def income(company):
print("Do you have any income from", company, "today?")
ans = confirm()
delay(0.45)
if ans == True:
total = input('What was your income from ' + company + ' today?\nIncome: $')
while isinstance(total, (float, int)):
print("Invalid amount! Please enter in $XX.XX format.")
total = input('Income: $')
if isinstance(total, (float, int)):
return total
print('Is $', total ,'correct?')
totalconfirm = confirm()
while totalconfirm == False:
total = float(input('Enter the correct amount: $'))
totalconfirm = confirm()
elif ans == False:
return False
You can print out the total in the format XX.XX (or X.XX or XXX.XX etc.) with "{:.2f}".format(total)
. This formats it as a float to two decimal places. You do not need to apply this formatting to any of the math, just the printing.
Checking if inputs are valid numbers can be done with
try:
val = float(userInput)
except ValueError:
# your code here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.