CoCalc Shared FilesErros.sagews
Author: Leon Denis
Views : 8

Tratamento de Erros no Sage

tg(x)

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> NameError: name 'tg' is not defined
k+1

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> NameError: name 'k' is not defined
lista=[1,2,3];lista[3]

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> IndexError: list index out of range
([5,6,7]).union([2,3,4])

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> AttributeError: 'list' object has no attribute 'union'
1/0

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> File "sage/rings/integer.pyx", line 1843, in sage.rings.integer.Integer.__div__ (/projects/sage/sage-7.3/src/build/cythonized/sage/rings/integer.c:12742) raise ZeroDivisionError("rational division by zero") ZeroDivisionError: rational division by zero
[1,2,3)

Error in lines 0-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "<string>", line 1 [Integer(1),Integer(2),Integer(3)) ^ SyntaxError: invalid syntax
for i in range(10):
if i%2==0:
print i


Error in lines 1-3 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "<string>", line 3 print i ^ IndentationError: expected an indented block
[1,2]+(1,2)

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> TypeError: can only concatenate list (not "tuple") to list
for i in x:
i=i+1

Error in lines 1-2 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> TypeError: 'sage.symbolic.expression.Expression' object is not iterable
load('texto.py')

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_salvus.py", line 3391, in load exec 'salvus.namespace["%s"] = sage.structure.sage_object.load(*__args, **__kwds)'%t in salvus.namespace, {'__args':other_args, '__kwds':kwds} File "<string>", line 1, in <module> File "sage/structure/sage_object.pyx", line 992, in sage.structure.sage_object.load (/projects/sage/sage-7.3/src/build/cythonized/sage/structure/sage_object.c:11186) sage.repl.load.load(filename, globals()) File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/sage/repl/load.py", line 263, in load raise IOError('did not find file %r to load or attach' % filename) IOError: did not find file 'texto.py' to load or attach
assume(x>0, x<0)

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/sage/symbolic/assumptions.py", line 515, in assume x.assume() File "sage/symbolic/expression.pyx", line 1743, in sage.symbolic.expression.Expression.assume (/projects/sage/sage-7.3/src/build/cythonized/sage/symbolic/expression.cpp:12576) raise ValueError("Assumption is %s" % str(s._sage_()[0])) ValueError: Assumption is inconsistent
20//2.3

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> File "sage/structure/element.pyx", line 1896, in sage.structure.element.RingElement.__floordiv__ (/projects/sage/sage-7.3/src/build/cythonized/sage/structure/element.c:16647) return coercion_model.bin_op(self, right, floordiv) File "sage/structure/coerce.pyx", line 1043, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (/projects/sage/sage-7.3/src/build/cythonized/sage/structure/coerce.c:8958) raise File "sage/structure/coerce.pyx", line 1039, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (/projects/sage/sage-7.3/src/build/cythonized/sage/structure/coerce.c:8896) return PyObject_CallObject(op, xy) File "sage/structure/element.pyx", line 1895, in sage.structure.element.RingElement.__floordiv__ (/projects/sage/sage-7.3/src/build/cythonized/sage/structure/element.c:16622) return (<RingElement>self)._floordiv_(right) File "sage/structure/element.pyx", line 1908, in sage.structure.element.RingElement._floordiv_ (/projects/sage/sage-7.3/src/build/cythonized/sage/structure/element.c:16756) raise TypeError(arith_error_message(self, right, floordiv)) TypeError: unsupported operand parent(s) for '//': 'Real Field with 53 bits of precision' and 'Real Field with 53 bits of precision'
var('4')

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_salvus.py", line 2922, in var return var0(*args, **kwds) File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_salvus.py", line 2884, in var0 v = sage.all.SR.var(name, **kwds) File "sage/symbolic/ring.pyx", line 759, in sage.symbolic.ring.SymbolicRing.var (/projects/sage/sage-7.3/src/build/cythonized/sage/symbolic/ring.cpp:9295) raise ValueError('The name "'+s+'" is not a valid Python identifier.') ValueError: The name "4" is not a valid Python identifier.
sage: x=10
sage: for i in x:


Error in lines 2-2 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "<string>", line 1 for i in x: ^ SyntaxError: unexpected EOF while parsing
%md
## ** Tratando Exeções **


## ** Tratando Exeções **

%md Imagine que um pesquisador necessite avaliar o inverso multiplicativo de valores contidos em uma certa lista de dados obtida atráves de um processo qualquer que inadivertidamente gerou valores iguais a zero. Naturalmente, o valor zero não possui inverso multiplicativo, portanto, um erro de exceção irá interronper o laço.

dados=srange(-1.2,1,0.4, universe=QQ)+srange(-1,1,0.2, universe=QQ)
print i, ' -> ', 1/i

-6/5 -> -5/6 -4/5 -> -5/4 -2/5 -> -5/2 0 ->
Error in lines 2-3 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 2, in <module> File "sage/rings/integer.pyx", line 1849, in sage.rings.integer.Integer.__div__ (/projects/sage/sage-7.3/src/build/cythonized/sage/rings/integer.c:12830) raise ZeroDivisionError("rational division by zero") ZeroDivisionError: rational division by zero
%md A interrupção de uma rotina por erro de exceção pode ser bastante inconviniênte. Por exemplo, imagine que um pesquisador necessite avaliar o inverso multiplicativo de valores contidos em uma certa lista de dados obtida atráves de um processo qualquer que inadivertidamente gerou valores iguais a zero. É natural que o laço $\verb|for|$ a seguir seja interropido  pela exceção $\verb|ZeroDivisionError|$ quando encontra o valor $\verb|i=0|$:


A interrupção de uma rotina por erro de exceção pode ser bastante inconviniênte. Por exemplo, imagine que um pesquisador necessite avaliar o inverso multiplicativo de valores contidos em uma certa lista de dados obtida atráves de um processo qualquer que inadivertidamente gerou valores iguais a zero. É natural que o laço $\verb|for|$ a seguir seja interropido pela exceção $\verb|ZeroDivisionError|$ quando encontra o valor $\verb|i=0|$:

dados=srange(-1.2,1,0.4, universe=QQ)+srange(0,1,0.3, universe=QQ)
print i, ' -> ', 1/i

-6/5 -> -5/6 -4/5 -> -5/4 -2/5 -> -5/2 0 ->
Error in lines 2-3 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 2, in <module> File "sage/rings/integer.pyx", line 1849, in sage.rings.integer.Integer.__div__ (/projects/sage/sage-7.3/src/build/cythonized/sage/rings/integer.c:12830) raise ZeroDivisionError("rational division by zero") ZeroDivisionError: rational division by zero
%md Para evitar interrupções na execução de seus comandos você deve tratar as execeções que podem surgir, isto é,

%md
Sage possui a estutura $\verb|try...except|$ permite que sua rotina seja executada até o final mesmo com a ocorrência de erros de exceção específicos. A sintaxe sintxe mais simplmes para o tratamento de erros de execeção é a que apresetamos a seguir:



Sage possui a estutura $\verb|try...except|$ permite que sua rotina seja executada até o final mesmo com a ocorrência de erros de exceção específicos. A sintaxe sintxe mais simplmes para o tratamento de erros de execeção é a que apresetamos a seguir:

for i in dados:
try:
print i, ' -> ', 1/i
except ZeroDivisionError:
print 'divisao por zero'


-6/5 -> -5/6 -4/5 -> -5/4 -2/5 -> -5/2 0 -> divisao por zero 2/5 -> 5/2 4/5 -> 5/4 0 -> divisao por zero 3/10 -> 10/3 3/5 -> 5/3 9/10 -> 10/9 laço encerrado
var('n')

n
int(1.5)

1
int(e)

2
int('1.0')

Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> ValueError: invalid literal for int() with base 10: '1.0'