3

I've written a BMI calculator but I'd like there to be a way to ensure the user only types numbers so, if something else was input the question was to be asked again. Here's some of my code.

#Ask whether metric or imperial is to be used and ensures no typing errors
measure = input("Would you like to use Metric or imperial measurements? Please type i for imperial or m for metric  \n")

while(measure != "i") and (measure != "m"):
    measure =input("Please type a valid response. Would you like to use Metric or imperial measurements? Please type i for imperial or m for metric")

#Asks the users weight
if(measure == "i"):
    weights = input("Please type in your weight in stones and pounds- stones=")
    weightlb = input("- pounds=")
    weights = int(weights)
    weightlb = int(weightlb)
    weight = (weights*14)+weightlb

elif(measure == "m"):
    weight = input("Please type in your weight in kilograms=")
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
nitrogirl
  • 39
  • 1
  • 1
  • 9

2 Answers2

3

You can simply use a try, except loop plus an while loop. Here's what I mean:

intweight = 0
while True:
    try: 
        weight = float(input())
    except ValueError:
        print "Please enter a number"
    else:
        break
        intweight = weight

The while loop will force the user to enter a string until it only has numbers. The program will try to convert the string into a number. If there are letters, the except part will be activated. If the conversion is successful, the else part will activate, breaking the loop. I hope this helps you!

Anthony Pham
  • 3,096
  • 5
  • 29
  • 38
  • This goes well with the Python philosophy: [Easier to ask for forgiveness than permission](https://docs.python.org/2/glossary.html#term-eafp). I would wrap that in a function as this is used in several part of the program, though. – Sylvain Leroux Jan 31 '15 at 14:48
  • Sorry, bit of a newbie, do I just paste this under the kilograms part? thank you for your help :) – nitrogirl Jan 31 '15 at 14:49
  • this goes in place of your `while`-loop where you ask for `input("Please ... metric")` – RvdBerg Jan 31 '15 at 14:57
  • You can use `while True`, and instead of `integer = 1` use `break` after `intweight = weight` – user Jan 31 '15 at 14:59
  • But that while loop ensures a metric or imperial is chosen, its not anything to do with the numbers? I want it to re-ask for the users weight if for example the user types a letter or symbol. – nitrogirl Jan 31 '15 at 15:02
  • The while loop insures a number is chosen. If there is a letter, the program will ask the user to re-try. – Anthony Pham Jan 31 '15 at 15:19
  • You can use this code wherever you need the user to only type in numbers – Anthony Pham Jan 31 '15 at 15:21
1

Its what that str.isdigit is for :

while( not measure.isdigit()) :
     measure =input("Please type numbers only ")
Mazdak
  • 105,000
  • 18
  • 159
  • 188