I have the following code:
def right_rounding(min_vol):
try:
splitted = str(min_vol).split('.')
if float(splitted[0]) >= 1:
return 0
else:
return len(splitted[1])
except Exception as e:
print("Error code =",mt5.last_error())
print(e, 'error ', traceback.format_exc())
pass
It works right most of the time but sometimes it gives index out of range
index out of range
It's because splitted, which is of type str, is of length 1.
You can try printing the list splitted and you'll see that you have a list with just 1 element in it, and that would be min_vol.
When you split a string with some delimiter (in this case it is .), the returned value will be the string itself if the delimiter doesn't exist.
I am not sure what you're trying to achieve with that code, but the issue is that there is no splitting[1] because the list doesn't have an element in the 1st index.
If you want to access the last element of the list, you can enter -1 as the index and it will work.
Related
result = []
try:
for i in range(len(ass)):
int(df['sku'][i])
except ValueError:
result.append(df['sku'][i])
I need to collect all the errors in a list. Tell me, please, the code above adds only the first error, I need everything.
After iterating over all sku values, only those that cannot be converted to int should be included in the list.
You can move the try...except inside the loop:
result = []
for i in range(len(ass)):
try:
int(df['sku'][i])
except ValueError:
result.append(df['sku'][i])
You can also use isdigit() with a list comprehension as follows:
result = [val for val in df['sku'] if val.isdigit()]
However, you should note that isdigit() will not work in some cases e.g. those with leading signs.
As an example, '+1' will convert to an integer type fine with int() but will return False with is isdigit(). Similarly, -1 will convert fine with int() but return False with isdigit().
Further information can be found int the documentation:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
You'd want the try-except in the loop:
result = []
for i in range(len(ass)):
try:
int(df['sku'][i])
except ValueError:
result.append(df['sku'][i])
But if it's really a list of non-digit SKUs you want,
result = [sku for sku in df['sku'] if not sku.isdigit()]
This should work:
result = []
for i in range(len(ass)):
try:
int(df['sku'][i])
except ValueError:
result.append(df['sku'][i])
This piece of code will ask for input, compare input with content of lists and, if input and content match, return input.
If input is not in list user will be asked again for input.
def get_input(tested_list):
corect_input = False
while not corect_input:
try:
# we are comparing input to list of lists content
my_input = str.lower((input("Enter here: ")))
for line in a_list:
if my_input == line[2].lower():
return my_input
except ValueError:
print("????")
else:
corect_input = False
Now questions (I'm very beginner. Try-Except-Else is all very new for me) :
Is there any reason here to include 'except' line? Since input is converted to string, I can't see way to input anything what will cause any error.
What kind of error shall I use after 'except'.
How shall I write this piece of code to be better / cleaner/ more pythonic? :) .
thank you
First issue to note is that a_list in your function should be replaced by tested_list. a_list has not been defined and will cause an error.
There are at least 2 possible errors you can face:
AttributeError, if the 2nd index of a sublist in tested_list is not a string, e.g. if it is an integer.
IndexError, if the 2nd index of a sublist in tested_list does not exist, e.g. if the sublist is of length 2.
However, to make your try / except clause useful in this context, you need to define it within the for loop. Below is an example.
def get_input(tested_list):
correct_input = False
while not correct_input:
my_input = str.lower((input("Enter here: ")))
for line in tested_list:
try:
if my_input == line[2].lower():
return my_input
except (AttributeError, IndexError):
print("An error has occurred")
else:
correct_input = False
I have an array and an input, if I input something I want to use .startswith() with my array, for example if I have this:
Array = ['foo','bar']
And if I input "fo" I want it to match it with "foo" and then return the index, in this case 0. How would I do this?
MaryPython's answer is generally fine. Alternatively, in O(n) instead of O(n^2), you could use
for index, item in enumerate(my_list):
if item.startswith('fo'):
print(index)
I've used enumerate to walk the index with the item
Note that Marky's implementation fails on this array
['fo','fo','fobar','fobar','hi']
because .index always returns the first instance of a repeated occurrence (but otherwise his solution is fine and intuitive)
Here is one solution. I iterated through the list and for each item checked if they start with the string 'fo' (or whatever your want to check with). If it starts with that string it prints the index of that item. I hope this helps!
Array = ['foo', 'bar']
for item in Array:
if item.startswith('fo'):
print(Array.index(item))
#!/usr/bin/python
# -*- coding: ascii -*-
Data = ['bleem', 'flargh', 'foo', 'bar' 'beep']
def array_startswith(search, array):
"""Search an iterable object in order to find the index of the first
.startswith(search) match of the items."""
for index, item in enumerate(array):
if item.startswith(search):
return(index)
raise(KeyError)
## Give some sort of error. You probably want to raise an error rather
## than returning None, as this might cause a logic error in the
## later program. I think KeyError is correct, based on the question.
## See Effective Python by Brett Slatkin, Page 29...
if __name__ == '__main__':
lookfor='fo'
try:
result=array_startswith(lookfor, Data)
except KeyError as e:
print("'{0}' not found in Data, Sorry...".format(lookfor))
else:
print("Index where '{0}' is found is: {1}. Found:{2}".format(lookfor,
result, Data[result]))
finally:
print("Try/Except/Else/Finally Cleanup happens here...")
print("Program done.")
In python i have this code
if record[0][1]:
the problem is.. when mysql does not return anything and thus..
record[0][1]
has no data..
this python code fails:
if record[0][1]:
IndexError: tuple index out of range
i simply want it to move on to the "else" statement or simply consider this if statement as .. invalid given that
record[0][1]
has no value. or data.. ( incoming stuff from mysql )
try:
if record[0][1]:
# Do stuff
except IndexError:
pass
You can use a try...except or use a short-circuiting check on outer tuple.
if len(record) > 0 and len(record[0]) > 1 and record[0][1]:
I'm trying to add items to 2D array "groups". I'm getting error. I know why, but I don't know how to solve it. I tried groups[1].add but it did not work. The array groups[1] doesnt exists when I am trying to append. Is there a way, how to make this array only when it is necessary (when trying to append or add or insert)?
def sortResults(results,pattern):
ordered=results
ordered.sort()
groups= [[]]
for r in results:
print r
tuple=evaluate(pattern,r)
print(tuple)
if tuple[0]==1:
groups[0].append(r)
elif tuple[0]==2:
groups[1].append(r)
for group in groups:
print(group)
for item in group:
if item != 0:
ordered.remove(item)
ordered.append(item)
return ordered
I'm getting this error:
groups[1].append(r)
IndexError: list index out of range
Thanks in advance!
Why not use:
groups = [[], []]
instead if you are going to append to two groups? Then you won't run into that problem.
You can always remove it again if it remains empty, or you can use exception handling:
elif tuple[0]==2:
try:
groups[1].append(r)
except IndexError:
groups.append([r])
as the list missing is only a problem once.