0

I need to make a change calculator in python and I want to make it so the user cannot input letters or symbols, I have tried lots of things and I can't get it to work. I have used a while loop to stop the user from inputting anything below 0.01 and so it must be possible to do this for letters.

given = float(input("How much money was given?\n"))#Asks for the amount of money given
while given < 0.01:#Prevents any digits 0 or lower from being inputted
    print("That is not a valid amount")
    given = float(input("How much money was given?\n"))
    if given > 0.01:
        break
while True:#Prevents anything not a digit from being inputted
        print("That is not a valid option")
while given.isalpha():#Prevents anything not a digit from being inputted
        print("That is not a number")
        given = float(input("How much money was given?\n"))

the error message says that it cannot change string to integer/float

some other bits don't work because i tried different things from online but i particularly need help with the bit i asked about. Thanks again

  • 2
    Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – jonrsharpe Feb 23 '17 at 21:01
  • 1
    can you post what you've tried, and why it's not working? – Aaron Feb 23 '17 at 21:06

3 Answers3

0

Use this to test for a number. Using int(thing) will throw up a ValueError if thing is not a number.

try:
    given = int(input("Enter a number: "))
except ValueError:
    print("Not a number")
0

If you really want to only allow the digits 0-9:

user_input = input('Enter some digits: ')
print(all(c.isdigit() for c in user_input))
BallpointBen
  • 9,406
  • 1
  • 32
  • 62
0

The issue is that you are converting your input to a float right at the beginning. You get an error if the input is a string and hence cannot be converted to a float.

Also you need to rearrange your code a little. This is a super simple example with all your conditions:

while True:

    given = input("How much money was given?\n")
    #Asks for the amount of money given

    if any(c.isalpha() for c in given):
        # make sure to check each letter
        print("Not a number")
    elif float(given) < 0.01:
        print("Enter number greater than 0.01")
    elif float(given) > 0.01:
        break
shish023
  • 533
  • 3
  • 10