Python - Declaration of a variable in Try

Asked

Viewed 104 times

0

I am trying to create a menu in Python and I came across a part of mathematical calculations where I would like to insert an error condition if the user inserted a letter in a place where he can only receive a number.

I’m using loops and my problem is that I’m using the function try, I have to declare a variable within that function for it to be executed. I think, but then - later on in the program -, I can’t "call it" because it was declared locally!

Here is my sample code:

while loop2:
    try:
        a = int(input("Introduza o primeiro número: \n"))
    except ValueError:
        print("Introduza um número inteiro!")
    else:
        break
    try:
        b = int(input("Introduza o segundo número: \n"))
    except ValueError:
        print("Introduza um número inteiro!")
    else:
        break
    oper = str(input("Introduza o sinal de operação: \n"))
    if oper == "+":
        print(f"O resultado é: {a + b }!")

In the last line of code I exemplified, neither "a" and neither "b" are defined. Therefore, I won’t be able to do any operation!

  • 3

    Why does it say that the variable will not exist outside the try?

2 answers

4


Your premise is wrong.

The block try/except does not create a new context of variables, ie any variable you set within your block try will exist outside the block as well. See the example:

try:
  number = int("42")
except TypeError:
  pass

print(f"Número: {number}")  # Número 42

See working on Repl.it or in the Ideone

What happens is that you used the structure else of try/except/else and put a break in it. The else of this structure at all times will be called when no exception is cast on try and when executed it will stop its loop. That is, whenever the user gives a valid number, it will fall into the else and your loop of repetition will end, never coming to your print where the variables supposedly did not exist.

For your problem, there is no need to use the else in the try.

2

One of the possible ways to resolve this issue is:

while True:
    try:
        a = int(input('Introduza o primeiro número: '))
        break
    except ValueError:
        print('Introduza um número inteiro!')

while True:
    try:
        b = int(input('Introduza o segundo número: '))
        break
    except ValueError:
        print('Introduza um número inteiro!')

oper = input('Introduza uma das operações [+/-]: ')
while (len(oper) != 1) or (oper not in '+-'):
    print('Valor INVÁLIDO!')
    oper = input('Introduza uma das operações(+/-): ')

if oper == '+':
    soma = (a + b)
    print(f"O resultado é: {soma}")
else:
    subtracao = (a - b)
    print(f'O resultado é: {subtracao}')

Note that in this code the 1st block while check whether the value of to is an integer number. If so, the code stores the entered value in the variable a. If no, an integer value will be asked again to be inserted into the variable a.

In the 2nd block while will be checked if the entered value is also an integer value. If positive, the code stores the entered value in the variable b. If no, an integer value will be asked again to be inserted into the variable b.

Then it is requested the character for the operation. If the character typed is single and is contained in the string +-, the operation of Addition or subtraction, respectively.

  • So far I just do not give a +1 because it remains to explain to the AP that in python "the block try/except does not create a new context of variables". Why do you have to explain this? For example to a developer who came from js it comes with the perception that the block try/catch creates its own variable context and an analogous code try{let a=10; throw Error}catch(e){console.log(a)} will generate the error Uncaught Referenceerror: a is not defined

  • @Augusto Vasques, I didn’t explain the difference between the try/except of PYTHON and the tra/catch of JAVA SCRIPT for the simple fact that the author of the question did not refer to JAVA SCRIPT but, yes, to PYTHON.

  • I don’t think I explained myself, sorry for the misunderstanding but I quoted the JAVA SCRIPT as an example, I could cite examples other languages that have the same behavior similar to context variables so JS was the choice to be something common domain understandable to a greater number of users.

  • Regarding the urgency of the explanation starts from the premise that the PA in its question explained the following argument: ... my problem is that when using the Try function, I have to declare a variable within that function in order for it to be executed.

  • I think, but then - later on in the program -, I can’t "call it" because it was declared locally! * and this argument is false for the exceptional treatment does not create local context of variables which can be proved by this example leading to believe that the AP is having difficulty adapting to the python runtime model.

  • Apologizing for the text but I thought I should explain the logic behind my first comment by believing that I was not wise in the choice of words.

  • 1

    @Augusto Vasques, Good afternoon! Big hug!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.