I have a function in python that does error checking on a string. If the function finds an error it will return a tuple with an error code and an identifier for that error. Later in the program I have the function that handles the error. It accepts the tuple into two variables.
errCode, i = check_string(s,pathType)
check_string is the function that produces the tuple. What I want it to does is return just zero if there is no error. When a zero is returned the above code seems to fail because there is nothing for the variable i.
Is there an easy way to get this to work or do I just need to have the program return a tuple of 0 and 0 if no error is found?
I would use the exception system for this.
class StringError(Exception):
NO_E = 0
HAS_Z = 1
def string_checker(string):
if 'e' not in string:
raise StringError('e not found in string', StringError.NO_E)
if 'z' in string:
raise StringError('z not allowed in string', StringError.HAS_Z)
return string.upper()
s = 'testing'
try:
ret = string_checker(s)
print 'String was okay:', ret
except StringError as e:
print 'String not okay with an error code of', e.args[1]
You could use None as the value for error
def check_string(s,pathType):
# No error
return (None, i)
Why not simply check the length of the tuple before trying to retrieve the values?
err_tup = check_String(s, pathType)
if len(err_tup) == 2:
errCode, i = err_tup
else: # assuming it can only be 1 otherwise
errCode = err_tup
This would work without making any changes to the rest of your code that generates the tuple, and is semantically clear.
Based on "Simple is better than complex."
If you are going to return zero:
foo = func()
if not foo:
print 'No errors'
else:
# foo is tuple
Related
I'm learning python , and decided to write a program which takes a undefined number of inputs and gives the 'sum' and 'max' from math module , where the inputs are first stored in a list (b) and then passed to a function . I'm not sure if there is an another way to do this ( actually used *args and a lot of 'if' conditions before i could get a desired result, and my current code is the closest to it)
I'm fairly new to stackoverflow too , so tips on how i presented my question and how i can improve it will help too~
def dc(args):
print('sum :', sum(args) ,'Max :', max(args))
return
b=[]
while True:
a = input('->')
if a == "":
break
b.append(int(a))
print(dc(b))
#so function dc returns sum and max. And used while True keep giving input untill a blank line - "" is given before adding them to list b[]
what I expected ...
->1
->2
->3
->
sum : 6 Max : 3
What I got ...
->1
->2
->3
->
sum : 6 Max : 3
None
And i don't understand where the None came from
Firstly the returning of None has nothing to do with the While loop.
What you have defined is a void function. There are two types of functions, a value(s) returning type of function and a void function.
Void functions do not return anything. And when a function does not return anything, it returns None value, which is like 'nothing' in regular English.
Do not use values like 'a' or 'b' as variable names, use values that are descriptive of what that variable holds.
I also recommend having a data-type check with a try block. Refer the code below and the outputs shown. Here the function is returning two values, the sum(input_list) and max(input_list).
def max_and_sum_of_list(input_list):
print('Sum :', sum(input_list) ,'Max :', max(input_list))
return sum(input_list), max(input_list)
input_list=[]
while True:
input_number = input('->')
if input_number == "":
break
try:
input_list.append(int(input_number))
except ValueError as value_error:
print("Incorrect input data-type", str(value_error))
sum_of_numbers, max_of_numbers = max_and_sum_of_list(input_list)
Try out this code
def dc(args):
return 'sum :', sum(args) ,'Max :', max(args)
b=[]
while True:
a = input('->')
if a == "":
break
b.append(int(a))
print(dc(b))
This happened because you have returned a None object and things actually go fine with the print() function. Here👆, I have returned the sum of args and max of args instead of printing it as it is a function
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.
I wanted to create simple code to test if number is odd or even.
I am using Python 2.7.3.
def oddoreven(a):
try: int(a)
except: return "Error"
if a%2==0: return 1
else: return 0
Instead the code fails with error: TypeError: not all arguments converted during string formatting. The error points to the line beginning with if a%2==0....
While researching this problem I found examples indicating that code like this should work. For example answers to this question offer similar code as solution: python - checking odd/even numbers and changing outputs on number size
So what is wrong with my code?
It's because you first test if a can be converted to an int (which is fine), but then you ignore this test and keep going with the string you provided in argument.
Python is a dynamically typed language, but also strongly typed, which means you can change the type of a variable after it's been declared, but this change has to be explicit (more about this here).
In your case, it means you can't do if a % 2 == 0 if a is a string.
You could do this for instance:
def oddoreven(a):
try:
my_int = int(a)
except TypeError:
return "The argument provided could not be converted into an int"
if my_int % 2 == 0:
return 1
else:
return 0
the int function doesn't change the a in-place, you need to assign it to a :
>>> def oddoreven(a):
... try: a=int(a)
... except: return "Error"
... if a%2==0: return 1
... else: return 0
...
>>> oddoreven('2')
1
>>> oddoreven('5')
0
>>> oddoreven('a')
'Error'
As user2357112 stated. (int)a does not convert a to a int. so when you check its modulus you still must convert it.
def oddoreven(a):
try: int(a)
except: return "Error"
if int(a)%2==0: return 1
else: return 0
print oddoreven(32)
works fine.
As a side note, catching any exception is generally frowned upon. You may want to narrow it down like:
def oddoreven(a):
try: int(a)
except TypeError: return "Error"
if int(a)%2==0: return 1
else: return 0
print oddoreven(32)
So, I have this function below:
def remove_all(lst):
i = 0
while i < 10:
try:
print('Removing... ')
print(int(lst.pop()) + 10)
print("Removed successfully.")
# As soon as an IndexError is raised, jump to the following block of code...
except IndexError as err:
# if you encounter an indexerror, do the following:
print("Uh oh! Problems.")
return
#As soon as a Value error is raised, jump here.
except ValueError as err:
print("Not a number")
i = i + 1
What does the return do? There is no value after the return, so does it mean None or True?
And what is the point of having the return there if the value is none?
Thanks!
The return value is None.
In this context, the function never returns a value. The point of the return is to stop execution
The return statement can be used as a kind of control flow. By putting one (or more) return statements in the middle of a function, you could exit/stop the function.
This causes the function to exit when an IndexError is encountered, just without returning any value.
In your example, there is no return value.
Given you would call the function like this:
a = remove_all(lst)
a will be None because the function simply returns nothing.
To check the success of the function, you could implement it like this:
def ....
try:
...
exception 1:
your error handling...
return False
exception 2:
your error handling...
return False
continue function...
return True
When you then check the return value of your function, you will see if it has been executed till the end (True) or if it raised an error before (False).
However, this will not continue the execution of this particular function after one of the defined errors occurred.
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