1
  1. What is the indented lines directly below try: called/reffered to? I have heard "the body of try:" and "the expression of try:". Please clarify. (See user - poke´s - answer)

  2. What is try:, except:, while: etc. reffered to? Like True and False are reffered to as "statements". (See user - poke´s - answer)

  3. Is there any reason to change function1 into function2. The only difference between them is ValueError. The functions are only supposed to force the user to input an integer. (See user - poke´s - answer)

function1

def get_integer(LIMIT_PROMPT):
    while True:
        try:
            return int(input(LIMIT_PROMPT))
        except:
            pass

I have seen lots of except statement: and in the body/expression there is a piece of code that does something if an error occured in the body/expression of try:

I have used this particular function in two programs and have not run into any trouble.

function2

def get_integer(LIMIT_PROMPT):
    while True:
        try:
            return int(input(LIMIT_PROMPT))
        except ValueError:
            pass

1 Answers1

0

Like True and False are referred to as "statements"

True and False are both variables referring to singleton values of the bool type. As variables, they are atomic expressions.

try, except, while etc. are statements, or more accurately, compound statements because they contain a group of other statements. Usually you would refer to that group of statements as a block, as in other languages they are encapsulated within block creating tokens (e.g. { and }). In the Python specification, they are being referred to as suite.

The suites of each compound statement does not really have a special name, so I guess you could just call them “try suite”, “except suite” etc., or “try block” and “except block”.

Is there any reason to change this function into this (the only change is ValueError)

Usually, when you check for exceptions, you should be as specific as possible. If you know that what you do within the try block can throw an exception of type X, then catch/except exception X only.

Not specifying a type will make the except catch any exception including those you might not know of that they could be thrown there, so you would lose useful information there. There are a lot questions on SO that already handle that topic, so I’ll just lead you to a random one I just found. Exception management is language agnostic, so you can just apply what you read to Python.

Community
  • 1
  • 1
poke
  • 369,085
  • 72
  • 557
  • 602