2

We are learning exception handling. Did I do this correctly? Is ValueError the correct exception to use to catch strings being typed instead of numbers? I tried to use TypeError, but it doesn't catch the exception.

Also, is there a more efficient way to catch each exception in my four inputs? What is best practice here?

#Ask user for ranges. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input. while True: try: rangeLower = float(input("Enter your Lower range: ")) except ValueError: print("You must enter a number!") else: #Break the while-loop break while True: try: rangeHigher = float(input("Enter your Higher range: ")) except ValueError: print("You must enter a number!") else: #Break the while-loop break #Ask user for numbers. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input. while True: try: num1 = float(input("Enter your First number: ")) except ValueError: print("You must enter a number!") else: #Break the while-loop break while True: try: num2 = float(input("Enter your Second number: ")) except ValueError: print("You must enter a number!") else: #Break the while-loop break 
2
  • Does it work the way you expect when you run it? Commented Dec 2, 2019 at 3:24
  • Good point. Yes, it works as expected. However, I am still new and have found myself running code that I thought worked as intended, yet it was still written improperly. Anyways, it does seem to work flawlessly. Commented Dec 2, 2019 at 3:28

1 Answer 1

4

Here you are experiencing what is called, WET code Write Everything Twice, we try to write DRY code, i.e. Don't Repeat Yourself.

In your case what you should do is create a function called float_input as using your try except block and calling that for each variable assignment.

def float_input(msg): while True: try: return float(input(msg)) except ValueError: pass range_lower = float_input('Enter your lower range: ') ... 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.