1

Why does this code not work? No easy way to explain.

def main():
  while True:
    mon = input("What is the month? ( 1 - 12 )")
    try:
        mon = int(mon)
    except ValueError:
        print("Try again.")
    elif mon > 0 and mon < 13:
        break
    else:
        print("Try again.")
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • 4
    Please at least try to explain - there is no easy way to understand your question. What happens, and what do you expect should have happened? Also, as posted your indentation will produce a syntax error, so please post a [MCVE]. – Ken Y-N May 07 '18 at 00:12
  • 1
    Possible duplicate of [Why does Python not implement the elif statement on try statement?](https://stackoverflow.com/questions/32115375/why-does-python-not-implement-the-elif-statement-on-try-statement) – Ken Y-N May 07 '18 at 00:14
  • Did one of the solutions below help? Feel free to accept one if it did (green tick on left), or ask for clarification. – jpp May 11 '18 at 13:14

1 Answers1

0

There are a few changes you should make to your code for it to work.

You should use else as part of a try / except / else structure. Also use continue to signify explicitly where a loop will continue.

Your code is invalid as an if / else clause cannot start with elif.

Here is a working example:

def main():
    while True:
        mon = input("What is the month? ( 1 - 12 )")
        try:
            mon = int(mon)
        except ValueError:
            print("Try again.")
            continue
        if mon > 0 and mon < 13:
            break
        else:
            print("Try again.")
    return mon
jpp
  • 159,742
  • 34
  • 281
  • 339
  • You don't need the `continue` in the `except` block if you're going to put an `else` afterwards (you only need one of those things, not both). And you don't need the continue at the end of the inner `else` at all, since the end of the loop happens immediately afterwards already. – Blckknght May 07 '18 at 01:00
  • @Blckknght, You're right, it's not required. I'm not sure what the style guides say, but [elsewhere](https://stackoverflow.com/a/23294659/9209546) `continue` seems used even when unnecessary. – jpp May 07 '18 at 01:02
  • 1
    Hmm, perhaps it's just my personal style then, that I'd never use a redundant `continue`. I would probably use the first `continue` in your code instead of the `else`, but never the completely pointless one at the end. – Blckknght May 07 '18 at 01:10
  • @Blckknght, Agreed, that does make sense. – jpp May 07 '18 at 01:12