1

I am currently learning python and I was wondering if there is an easier way to validate user input. I am working on a Body Mass Index calculator. Even though the code is working, I feel like this is not the best practice and that there is an easier way to validate user input without using multiple while loops.

Right now my code is looking as follows.

print("#########################################################\n"
      "############## Body Mass Index calculator ###############\n"
      "#########################################################\n")


# asks user to input his height
height = input("Please enter your height in m: ")

# mechanism to check if the user input is valid input
while True:

    # checks if the user input is a float
    try:
        float(height)
        new_height = float(height)
        break

    # if the user input is not a float or a number, it prompts the user again for valid input
    except ValueError:
        print("Enter a valid height...")
        height = input("enter your height in m: ")
        print("")
        continue

weight = input("Please enter your weight in kg: ")

while True:
    # checks if the user input is a float
    try:
        float(weight)
        new_weight = float(weight)
        break

    # if the user input is not a float or a number, it prompts the user again for valid input
    except ValueError:
        print("Enter a valid weight...")
        weight = input("enter your weight in kg:")
        print("")
        continue

# calculating the body mass index
body_mass_index = new_weight / new_height**2

# printing out the result to the user
print("\nYour BMI is " + str(round(body_mass_index, 2)))
Tomcatn00b
  • 65
  • 7
  • 3
    When you recognize a repeating pattern of lines of code - this calls for a function! – Tomerikoo May 01 '21 at 00:44
  • @Tomerikoo, Thanks a lot for your help! I kind of had this feeling as well. I was not sure on how to achieve it according to the best practices :( – Tomcatn00b May 01 '21 at 00:53

1 Answers1

5

Repeated code like this is best put into a function. Here's an example.

def get_float_input(var, units):
    while True:
        value = input('enter your {} in {}: '.format(var, units))
        try:
            return float(value)
        except ValueError:
            print('Invalid entry!')

height = get_float_input('height', 'm')
weight = get_float_input('weight', 'kg')

There's a programming principle called DRY: Don't Repeat Yourself. If you have the same logic/functionality being utilized in multiple places, you should gather it into one place.

In addition to improving readability, this has the benefit of making your life a lot easier. As the great Larry Wall said (I'm paraphrasing), "The first great virtue of a programmer is laziness." Suppose you later wanted to make some change to the logic (for example, changing the message printed when the user enters an invalid string). With the DRY principle, you don't have to track down every single part in your code (which could be thousands of lines long) where you used this loop. Instead, you go to the one place where it's defined and make the change there. Presto!

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • Thanks a lot! I had the feeling I had to make use of a function but I could not figure out how. I will mark this solution as the answer! However, I do have a question out of curiosity. What are the dangers of re-using while loops like I did in my code, if there are any? – Tomcatn00b May 01 '21 at 00:52