I am having trouble understanding how to write a try except block that only runs one block or the other not just half the block and then move to the exception as seen in my example for emphasis I do not wish to run any portion of try if any line in try fails
x = 1
y = 1
try:
x = x+1
print(x)
x.append(1)
except:
print(x)
which returns
2
2
instead of returning
1
as I would of expected. This is problematic for me because I was foolishly under the impression that only except block would be executed upon try failure. I am scraping websites using beautiful soup and my allocation of a soup usually will throw the exception and the other block will run but unforeseen errors after this allows some lists to be appended then runs the exception block and appends them again. leaving me with lists of different lengths depending on where they fall within each block.
any help is much appreciated
You could reset the computed_result to value of x in except-block on error:
x = 1
y = 1
computed_value = 0
try:
computed_value = x + 1
#print(fallback_var)
computed_value.append(1)
print("Exceution succeed: keeping value")
except:
print("Exceution failed: resetting value")
computed_value = x
#print(x)
print(computed_value)
Let's go step by step:
Your code correctly executes x=x+1 (now x is 2).
Then it correctly executes print(x) (so it prints 2).
Then it tries to execute x.append(1) (and fails)
Since it has failed to append(1) it enters the except and executes print(x) (so it prints 2)
It outputs exactly what's expected.
This run both.
Your code
try:
x = x+1
print(x)
x.append(1)
except:
print(x)
When python start execution, it execute line by line
x = x + 1
After this x become 2.
then
print (x)
Print 2 as first in your output.
x.append(1)
Above statment raise exception which is caught by except clause in your code.
Please remember, x value is already change to 2 in x = x + 1 statment. In except when you do
print (x)
It print 2 again.
Related
I only want to return and print the error when the function is called, but it seems that the whole functions are being run when I print the function.
My expected output is only:
false
list index out of range
but I am getting:
false
false
false
list index out of range
I tried calling the function like this but did not work: print(test(error))
Question: How can I only print the error parameter and not the other parameter outside the function? Here is my code, Thanks:
def test(error=None, parameter1=None):
array = []
try:
if parameter1 == True:
print("true")
array[0]
else:
print("false")
array[0]
except Exception as e:
error = e
return error
test()
if test() is not None:
print(test())
You're running the function twice, once in the if statement, and then again in the print() statement.
If you only want to run it once, assign the result to a variable.
err = test()
if not err:
print(err)
This is happening because python is read line by line. This means that it will check the condition for parameter1 == True before going onto your statement that returns an error. Restructure the code so that it checks for an error before printing out "false". Example:
def test(error=None, parameter1=None):
array = []
try:
array[0]
except Exception as e:
error = e
return error
if parameter1 == True:
print("true")
else:
print("false")
if test() is not None:
print(test())
Additionally, the act of writing the if test() will call the function, which is why it printed false the first time. Then you called print(test()) which called it a second time, resulting in two "false"s being printed out.
For example,
def power(x, n):
res = 1
for i in range(n):
res *= x
return res
power('10',5)
Then, it will raise the error as follows.
TypeError: can't multiply sequence by non-int of type 'str'
Now, I try to use %debug in the new notebook cell to debug.
ipdb> x = int(10)
ipdb> c
However, in %debug, if I use c which means continue in ipdb, it can't continue to run with changed value x.
So, I wonder if there is any method to correct the value of a variable while debugging and continue to run.
Update:
This is just an example.
In fact, I want to run the code for a long time in some cases, and an error occurs midway. I want to correct the error and try to continue to run the code. You know, simply re-running can take a long time.
Check the below solutions:
x value should not be str type
Use power(10,5) instead of power('10',5)
OR
Convert value of x in the code:
def power(x, n):
res = 1
for i in range(n):
res *= int(x)
return res
print(power('10',5))
So I have this function (example):
def monty(x):
if abs(int(x)) == 1:
print("Cool!")
print("Took %s attempts.") % (z)
elif abs(int(x)) == 0:
print("Nope.")
else:
z = z + 1
y = x - 1
monty(y)
Now, of course, 'z' has not yet been defined, so when this function is run so that the 'else' statement is called, the program returns a NameError exception.
Well, ok. Let's try making the statement this:
else:
try: z
except NameError: z = 0
else: z = z + 1
y = x - 1
monty(y)
Also assume we added the same NameError catch to the 'if' statement.
The statement always returns 'z' as 0, as the variable is utterly forgotten when 'monty' is ran again. Ok, what if we try defining z outside of 'monty' first, and drop the NameError catch?
Well, it returns a NameError again, and if we instead keep the NameError catch, it still only ever outputs 0.
So, how do I make the function increase z every time it's called validly? In other words, how can I have the program silently count how many times a function was run, to be recalled later? Let's try to avoid adding another argument to the function, for the sake of user-friendliness.
Just add z as a keyword argument:
def monty(x, _z=0):
# ...
else:
_z = _z + 1
y = x - 1
monty(y, _z)
I renamed z to _z to indicate that it is an implementation detail the end-user doesn't need to worry about. Because keyword arguments have a default, the caller of monty() doesn't have to worry about it.
When I run my python program from terminal with python sumSquares.py, I get the following result: <function diffSum at 0x1006dfe60>
My program looks like this:
def diffSum():
sumSquares = 0
for i in range(0, 100):
sumSquares += i**2
squareSum = 0
for i in range(0, 100):
squareSum += i
squareSum **= 2
print (squareSum)
return sumSquares - squareSum
print(diffSum)
Even though I have a print statement at the end, it doesn't actually print the result that is returned; it just prints the function address. Any ideas why this is?
You need to call the function by adding parentheses after its name, as in:
print(diffsum())
I can't understand why this code:
x='aaaa'
try:
self.assertTrue(x==y)
except:
print (x)
generates me this error
AssertionError: False is not True
It should be handle it by
print(x)
EDIT
original code is:
try:
self.assertTrue('aaaa'==self.compare_object_name[1])
except:
print ('aaa')
#Space_C0wb0y I can't give you full code because it is not my code, and I don't have a permission.
You should include the code that defines the assertTrue method. From the output you get, I'd say that it actually does not throw an exception, but deals with it internally (thus the error message being printed, and not your value).
You can use the built-in assert statement of Python, which works as expected:
x = 'aaaa'
y = 'bbb'
try:
assert(x == y)
except:
print (x)
Output:
>>>
aaaa