Validate floating values from user input - python

This function will take a string as input. The string has the following properties:
Includes characters 0-9
May include period to denote cents. (If not
included assume 0 cents.)
May include $ sign.
May include commas as
digit separators.
Your function will convert the string into a floating point number. You may not use any built in commands like int or float. You must solve this problem by analyzing the characters in the string of text.
If the input is invalid, return -1 as the function's result.
If I input the following:
100.00
200
98.78
$1,009.78
Goat
exit
This is what the output looks like:
Determine Price with Tax.
Enter 'exit' at any time to quit.
Enter Amount ($X,XXX.XX):
Amount: 100.0
Tax: 6.0
Price w/ Tax: 106.0
Enter Amount ($X,XXX.XX):
Amount: 200
Tax: 12.0
Price w/ Tax: 212.0
Enter Amount ($X,XXX.XX):
Amount: 98.78
Tax: 5.93
Price w/ Tax: 104.71
Enter Amount ($X,XXX.XX):
Amount: 1009.78
Tax: 60.59
Price w/ Tax: 1070.37
Enter Amount ($X,XXX.XX):
Amount: -1
Tax: -0.06
Price w/ Tax: -1.06
Enter Amount ($X,XXX.XX):
My code is:
def price_to_int(text):
res = 0
valid = "$,.1234567890"
for l in text:
if l in valid:
res = float(text)
else:
return -1
return res
#---------You may not make any changes below this line-----------
print("Determine Price with Tax.")
print("Enter 'exit' at any time to quit.")
word = input("Enter Amount ($X,XXX.XX):\n")
while word.lower() != "exit":
d = price_to_int(word)
tax = 0.06
print("Amount:",round(d,2))
print("Tax:",round(d*tax,2))
print("Price w/ Tax:",round(d+d*tax,2))
word = input("Enter Amount ($X,XXX.XX):\n")
The only thing wrong is the function definition. My code works up until I input '$1009.78'. I am specifically asked to only rewrite the function definition and not change anything else.

Your current solution does not seem right to me. You are iterating over your string character-by-character, coercing each argument. You'd want to convert the entire string at once (otherwise, how are you going to get your float?).
Would you like a solution that does exception handling using try ... except?
def price_to_int(text):
clean_text = text.lstrip('$').replace(',', '')
try:
return int(clean_text)
except:
try:
return float(clean_text)
except ValueError:
return -1
This solution cleans your string and attempts to cast to float. If the conversion is not possible, an error is raised and handled, and -1 returned.
Details
str.lstrip removes the leading $ character
str.replace removes commas (when the second argument is the empty string)
try ... except ValueError: ... will attempt to run code inside the try block while waiting to catch a ValueError exception. If the exception is raised, the code inside the except block is executed (otherwise no).

Related

Getting discounted price for amount of items from user input

I just completed my pre-course assessment.
The project was:
A cupcake costs 6.50. If you purchase more than 6 cupcakes, each of them will cost 5.50 instead, and if you purchase more than 12, each of them will cost 5.00 instead.
Write a program that asks the user how many cupcakes they want to purchase, and display the total amount they have to pay.
My inputs have been:
amt=input("How many cupcakes would you like to but? ")
if amt>=6:
disc = amt*0.12
elif amt>=12:
disc=amt*0.24
print(disc)
I can't seem to get the code running. Can anyone please dump it down for me?
THE COMPLETE SOLUTION TO YOUR PROBLEM IS:
amt=int(input("How many cupcakes would you like to but? "))
if amt <= 6:
pancake_price_650 = 6.50
price_inferior_6 = amt * pancake_price_650
print(price_inferior_6)
elif amt > 6:
pancake_price_550 = 5.50
price_superior_6 = amt * pancake_price_550
print(price_superior_6)
elif amt > 12:
pancake_price_500 = 5.00
price_superior_12 = amt * pancake_price_500
print(price_superior_12)
You were wrong in constructing the logic of conditions.
Also, you haven't converted the input to a string. Input is always read as a string, in your code you haven't read it as an integer. Convert string input to int using int(), because int() transforms a string into an integer. You need to add int before input, but put it in parentheses.
Python takes input in string format, you need to cast the input into int but in your code, you're comparing a string with int in the conditionals.
amt=int(input("How many cupcakes would you like to but? "))
if amt>=6:
disc = amt*0.12
elif amt>=12:
disc=amt*0.24
print(disc)

Need help understanding the format ".2f" command and why it is not working in my code

I'm practicing on my format statements, but i'm not quite understanding how it works. I am specifically trying to understand the format command using the ".2f" command this is the code i currently have, the second line runs before it returns and error:
salesTax = 0.08
salesAmount = str(input('Enter the sales amount: '))
print ('The sales amount is', format('$'+salesAmount,
'.2f'))
print ('The sales tax is', format("$"+'.2f'))
print('The total sale is', format("$"+totalSales*salesTax,
'.2f'))
input("\nRun complete. Press the Enter key to exit.")
I am trying to make a script, that displays the output of the following sample run:
//Sample run:
Enter the sales amount: 1234
The sales amount is $ 1,234.00
The sales tax is $ 98.72
The total sale is $ 1,332.72
Run complete. Press the Enter key to exit
TL;DR
print('The sales amount is $', format(salesAmount, '.2f'))
Breaking it down:
Convert the number to string formatted as 2 decimal places (.2 portion) with floating point representation (f portion).
format(salesAmount, '.2f')
Now that you have a string, you join it with either pass to print or you could join to previous code with + or whatever.
'The sales amount is $' + the_formatted_number
.2f should be outside of the format method.
eg try print("{:.2f}".format(12.345678))
format is a built-in function that takes two arguments: value and format_spec.
format('$' + salesAmount, '.2f')
Will give you an error because it is expecting a number or a string representation of a number as value to apply the format you have provided. You will get an error:
ValueError: Unknown format code 'f' for object of type 'str'
format(salesAmount, '.2f')
This will work properly.
Note: If you are using Python 3.6+ you can also use an f-string:
f"{12.345678:.2f}"
The syntax is
format(value, format_spec)
When you use a .2f format, the value should be a float, not a string, so you need to convert the input to float (input() returns a string, there's no need to use str() on the result. And you can't concatenate $ to the value before formatting it, you need to concatenate that to the result.
You also used a nonexistent variable totalSales in your print() calls, it should be salesAmount.
salesTax = 0.08
salesAmount = float(input('Enter the sales amount: '))
print ('The sales amount is', '$' + format(salesAmount, '.2f'))
print ('The sales tax is', '$' + format(salesTax*salesAmount, '.2f'))
print('The total sale is', '$' + format(salesAmount + salesAmount*salesTax, '.2f'))
input("\nRun complete. Press the Enter key to exit.")
That said, this use of the format() function is not common these days. It's easier to use an f-string or str.format(), which allows you to embed the format spec in a string with the plain text, and format multiple values together, e.g.
print("The sales amount is ${.2f}".format(salesAmount))

Python bank ATM

So I have a homework on coding a bank ATM machine and I have done most of the code but I do not seem to make work like the professor stated "If the user enters an invalid numeric value, inform the user as such. If the user enters a valid number between 0 and 100, display the amount of funds left in the account"
example:
kitten : "Invalid Entry".
20.5 : "Your account has $79.50 remaining"
My code so far:
amt = int(input("Withdraw amount: "))
if amt <= 0:
print("Invalid Amount")
else:
print{"Invalid Entry")
if amt > 100:
print("Not enough funds in account")
if (amt >=0 and amt <=100):
print("Your account has ${0:1.2f} remaining." .format(100-amt))
My issue is that when I enter 20.5 it give me an error
"ValueError: invalid literal for int() with base 10: '20.5'"
The second issue is when I enter a string "ValueError: invalid literal for int() with base 10: 'kitten'"
The reason why entering 20.5 gives you an error is because in the amt variable, it is looking for an integer to be inputted. In python, any number with a decimal is considered a float.
The code for the amt variable is currently
amt = int(input("Withdraw amount: "))
For the amt variable to have a number with a decimal as acceptable input, the amt variable should be this:
amt = float(input("Withdraw amount: "))
You are converting everything to an int, so putting in strings and doubles will give you errors. You need to check the content of your input before blindly converting it to an int.
You need to think about what your code is actually doing instead of just blindly changing things until they work without understanding why.

Python float numbers and correct use

I am typing a program for my class, the problem is worded very odd, but I have put in my code for the problem, am I declaring the numbers as float correctly?
Simple question but I'm keeping my mind open to other ways of doing things.
print " This program will calculate the unit price (price per oz) of store items,"
print " you will input the weight in lbs and oz, the name and cost."
item_name = (input("Please enter the name of the item. "))
item_lb_price = float(input("Please enter the price per pound of your item "))
item_lbs = float(input("please enter the pounds of your item. "))
item_oz = float(input("plese enter the ounces of your item. "))
unit_price = item_lb_price / 16
total_price = item_lb_price * (item_lbs + item_oz / 16)
print "the total price per oz is", unit_price
print "the total price for", item_name, "is a total of", total_price
Your floats are fine.
You need to use raw_input though to get a string back.
input("Enter a number") is equivalent to eval(raw_input("Enter a number")). Currently the code tries to evaluate the input as code (run as a python expression).
15:10:21 ~$ python so18967752.py
This program will calculate the unit price (price per oz) of store items,
you will input the weight in lbs and oz, the name and cost.
Please enter the name of the item. Apple
Traceback (most recent call last):
File "so18967752.py", line 6, in <module>
item_name = (input("Please enter the name of the item. "))
File "<string>", line 1, in <module>
NameError: name 'Apple' is not defined
Other comments:
For your multiline banner at the top, declare the string as a multiline string and print that.
Check to make sure the ranges make sense for the inputs (validate). Of course, if this is for a class you may not have reached this point (Seen if/else?)
Be explicit with your constants to make them floats to make sure it doesn't default to integer division
Slightly cleaned up form:
banner = '''
This program will calculate the unit price (price per oz) of store items.
You will input the weight in lbs and oz, the name and cost.
'''
print banner
item_name = raw_input("Please enter the name of the item. ")
item_lb_price = float(raw_input("Please enter the price per pound of your item."))
item_lbs = float(raw_input("Please enter the pounds of your item."))
item_oz = float(raw_input("plese enter the ounces of your item."))
unit_price = item_lb_price / 16.0
total_price = item_lb_price * (item_lbs + (item_oz / 16.0))
print "The total price per oz is", unit_price
print "The total price for", item_name, "is a total of", total_price
if it is python 2 you should be using raw_input instead of input.
if it is python 3 you should be enclosing the values you want to print in parentheses.
yes you are using the float function correctly but are not verifying that the input is correct. it is liable and even likely to throw errors.
besides the program is not correct for python 2 because of the input() and not correct for python 3 because of the use of the print statement.
And you should devide by a float: 16.0 instead 16.
Division in python is per default using integers, so if you want a floating point result you should divide by 16.0
unit_price = item_lb_price / 16.0

IF statement error new variable input python

The problem here is that I just cant get python to check if Currency1 is in string, and if its not then print that there is an error,but if Currency1 IS in string then move on and ask the user to input Currency2, and then check it again.
You can use try-except:
def get_currency(msg):
curr = input(msg)
try:
float(curr)
print('You must enter text. Numerical values are not accepted at this stage')
return get_currency(msg) #ask for input again
except:
return curr #valid input, return the currency name
curr1=get_currency('Please enter the currency you would like to convert:')
curr2=get_currency('Please enter the currency you would like to convert into:')
ExRate = float(input('Please enter the exchange rate in the order of, 1 '+curr1+' = '+curr2))
Amount = float(input('Please enter the amount you would like to convert:'))
print (Amount*ExRate)
output:
$ python3 foo.py
Please enter the currency you would like to convert:123
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert:rupee
Please enter the currency you would like to convert into:100
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert into:dollar
Please enter the exchange rate in the order of, 1 rupee = dollar 50
Please enter the amount you would like to convert: 10
500.0
You were actually trying for:
if type(Currency1) in (float, int):
...
but isinstance is better here:
if isinstance(Currency1,(float,int)):
...
or even better, you can use the numbers.Number abstract-base class:
import numbers
if isinstance(Currency1,numbers.Number):
Although ... Currency1 = str(raw_input(...)) will guarantee that Currency1 is a string (not an integer or float). Actually, raw_input makes that guarantee and the extra str here is just redundant :-).
If you want a function to check if a string can be converted to a number, then I think the easiest way would be to just try it and see:
def is_float_or_int(s):
try:
float(s)
return True
except ValueError:
return False

Categories