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!
Why does it say that the variable will not exist outside the
try
?– Woss