1

Essentially I'm just wondering if there's any way to make this code more concise. I don't even really know how to properly ask the question, but is there a module or expression I could write or import to help?

while True:
    try:
        guess = int(input("Enter a number here: "))
        break
    except:
        print("Please try again.")

In free language it would probably look like:

test:
    dothing("user thing")
if issues:
    print("try again")
    try again

I'm trying to prevent an error from the user typing something like a string and breaking the entire program. If this seems stupid, I apologize; I'm starting to get into Python again after what is essentially years of not using it and I'm probably forgetting something simple.

Thank you guys so much in advance.

Timmitei
  • 15
  • 3
  • 2
    That is as short as it gets I guess. You can enclose it in a function and call that function. – Mohammad Yusuf Jan 19 '17 at 07:07
  • 1
    Please see http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response . You may want to wrap your code in a function if you want to get lots of integers from the user. BTW, it's considered bad style to use "naked" `except`, you should be explicit about which exception(s) you want to catch. FWIW, `try...except` is faster than equivalent `if...else` code if the exception doesn't occur, but it's much slower if the exception _is_ raised, but I guess that's a non-issue when you're sitting waiting for user input. – PM 2Ring Jan 19 '17 at 07:20
  • That's all I really wanted to know. Thank you both, and I'll try to impliment explicit exception catching in my code from now on. – Timmitei Jan 19 '17 at 07:20

1 Answers1

3

Your natural language remembers me old unstructured languages like Fortran 4 or old basics...

In those languages, we used to go to line references:

100    CALL INPUTVAL(IVAL, IERR)
       IF IERR == 0 GOTO 200
       PRINT 50
50     FORMAT('ERROR TRY AGAIN')
       GOTO 100

200    CONTINUE

It may look more natural at first sight, but it soon leads to spaghetti code. That's the reason why clean loops and strutured error handling (try except) were invented. Don't regret the old goto style and stick to standard structured constructs

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252