I recently started learning python3, and I am trying to write an exception.
I have this line, which is a list of words.
I want to match the word create to the list, sometimes it's there sometimes its not. When it's not there I get this error:
Traceback (most recent call last):
File "sub_process.py", line 17, in <module>
if (line.index("create")):
ValueError: 'create' is not in list
and I am fine with that. This is expected. So I thought if I wrote an exception to it the script could just continue on and keep doing stuff. So I an exception below and all its suppose to do is nothing. Catch the error and continue on.
line = line.split()
if line.index("create"):
print("basd");
except ValueError:
print("123");
But everytime i try to compile this I get syntax error at "except" and I am not sure why. It looks perfectly normal compared against all the tutorials that I could find.
Rather than using index, you should just be using the in operator, which returns a simple boolean:
if "create" in line:
print("basd")
else:
print("123")
This will not raise an exception so there is no need for try/except.
if/except is not a valid construct. Use try/except:
line = line.split()
try:
if line.index('create'):
print('basd')
except ValueError:
print("123")
Alternatively, you could avoid the exception and the try/except altogether:
line = line.split()
if 'create' in line:
print('basd')
else:
print("123")
You need to add try before the if statement:
line = line.split()
try: # added 'try'
if line.index("create"):
print("basd");
except ValueError:
print("123");
Also note, you don't need the semicolons at the end of statements, and it is generally frowned upon when they are used in that way.
As an alterintave to #Rosemans solution, you can do that all on one line:
print('basd') if "create" in line else print("123")
#use try block..
line = line.split()
try:
if line.index("create"):
print("basd")
except ValueError:
print("123")
Related
I'm working on analyzing tweets using twitter api and twython library when im trying to search for tweets with an index (to give how many tweets to consider), why I'm accidentally giving index greater than the actual tweets with my given term it is throwing error like below
[ C:\Users\thota\anaconda3\lib\site-packages\twython\api.py", line 532, in cursor
raise StopIteration
StopIteration]
How can I write a TRY AND EXCEPTION code to exclude this error and to continue the remaining execution
I don't see why you need to catch a "StopIteration" exception instead of trying to improve the code and avoid these kinds of errors.
But if you insist:
try:
#Your code
except StopIteration:
pass
I have a dataframe, which is not loaded into memory (and it should stay like that).
At some point in the script I apply a conversion with a dictionary to one of the dataframe columns in the following manner:
df['identifier'] = df.identifier.map(lambda identifier: alias_dict[str(identifier)],
meta=('identifier', str))
KeyError exceptions are not found out on this stage but just when I use to_csv so I try to handle them
try:
dd.to_csv(intersection_df, output, header=None, index=None, single_file=True, sep='\t')
except KeyError as err:
print(f'Unmatched key {err.args[0]}')
In case I encounter a KeyError, the writing to the file is stopped - is there a way to make the writing continue even if I get an exception at that stage?
The best thing to do, if you want to skip or remediate the failing lines but keep writing, is to put your try/except into the mapping function
def alias(identifier):
try:
return alias_dict[str(identifier)]
except KeyError:
return identifier
df['identifier'] = df.identifier.map(alias, meta=('identifier', str))
In this case, failures are passed through unchanged. You could turn them into None and filter them out in a second step, or the two steps could be combined with map_partitions.
Im gonna include the description of the task this code is supposed to do in case someone needs it to answer me.
#Write a function called "load_file" that accepts one
#parameter: a filename. The function should open the
#file and return the contents.#
#
# - If the contents of the file can be interpreted as
# an integer, return the contents as an integer.
# - Otherwise, if the contents of the file can be
# interpreted as a float, return the contents as a
# float.
# - Otherwise, return the contents of the file as a
# string.
#
#You may assume that the file has only one line.
#
#Hints:
#
# - Don't forget to close the file when you're done!
# - Remember, anything you read from a file is
# initially interpreted as a string.
#Write your function here!
def load_file(filename):
file=open(filename, "r")
try:
return int(file.readline())
except ValueError:
return float(file.readline())
except:
return str(file.readline())
finally:
file.close()
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print 123, followed by <class 'int'>.
contents = load_file("LoadFromFileInput.txt")
print(contents)
print(type(contents))
When the code is tested with a file which contains "123", then everything works fine. When the website loads in another file to test this code, following error occurs:
[Executed at: Sat Feb 2 7:02:54 PST 2019]
We found a few things wrong with your code. The first one is shown below, and the rest can be found in full_results.txt in the dropdown in the top left:
We tested your code with filename = "AutomatedTest-uwixoW.txt". We expected load_file to return the float -97.88285. However, it instead encountered the following error:
ValueError: could not convert string to float:
So Im guessing the error occurs inside the first except statement, but i don't understand why. If an error occurs when the value inside a file is being converted to float, shouldnt the code just go to the second except statement ? And in the second except it would be converted to string, which will work anyway ? I'm guessing i misunderstand something about how try-except(specified error)-except(no specified error) works.
Sorry for long post.
shouldnt the code just go to the second except statement ?
Nope: this "flat" try/except statement works only for the first try block. If an exception occurs there, the except branches catch this exception and straight away evaluate the appropriate block. If an exception occurs in this block, it's not caught by anything, because there's no try block there.
So, you'd have to do a whole lot of nested try/except statements:
try:
do_this()
except ValueError:
try:
do_that()
except ValueError:
do_this()
except:
do_that_one()
except:
# a whole bunch of try/except here as well
You may need to add an extra level of nesting.
This is terribly inefficient in terms of the amount of code you'll need to write. A better option might be:
data = file.readline()
for converter in (int, float, str):
try:
return converter(data)
except:
pass
Note that if you do converter(file.readline()), a new line will be read on each iteration (or, in your case, in any new try/except block), which may not be what you need.
No, only one of those except blocks -- the first one matching the exception -- will be executed. The behavior you are describing would correspond to
except ValueError:
try:
return float(file.readline())
except:
return str(file.readline())
def load_file(filename):
file=open(filename, "r")
try:
val = file.readline()
return int(val)
except ValueError:
try:
return float(val)
except:
return str(val)
finally:
file.close()
Ok, so I have a block of code that I am trying to debug, and I usually use Pythontutor.com to step through the code to see where it is going wrong. Problem is, the exact code works on the website, but not in my console.
row = []
row.append("Acid Arrow")
testList = ['Detect', 'Discern', 'Summon', 'Call', 'Binding']
nameList = row[0].split(' ')
print testList, nameList
a = list(set(testList) & set(nameList))
The error I am getting is this:
C:\Users\User\Dropbox\D&D\SpellBag>livingSpell.py
['Detect', 'Discern', 'Summon', 'Call', 'Binding'] ['Acid', 'Arrow']
Traceback (most recent call last):
File "C:\Users\User\Dropbox\D&D\SpellBag\livingSpell.py", line 121, in <module>
sb = spellBook(r'allSpells.csv')
File "C:\Users\User\Dropbox\D&D\SpellBag\livingSpell.py", line 27, in __init__
a = list(set(testList) & set(nameList))
TypeError: 'str' object is not callable
The above code works flawlessly on PythonTutor, but fails when I run it in the console. What it is intended to do is check if a word from the list is in the spell name, which if any of them are, the spell is passed over and it moves on. It should be returning an empty list, but instead I get the error.
The line that has the error is a = list(set(testList) & set(nameList)), and the error says "'str' object is not callable." This means the Python interpreter tried to call a function and found out it wasn't actually a function. This is the same error you would get if you typed "bad_code"(), since the string "bad_code" is not a function.
It's impossible to say exactly which of the two is having an issue, but either list or set has been overwritten and is now a string rather than the default functions provided in Python. That snippet of code works fine by itself in pythontutor.com because the offending line of code happens somewhere before it in your file (the error says you have 22 lines of code beforehand). In fact, if you started a blank file and only had the snippet you posted here on StackOverflow, it would run perfectly. Check for anything like list = ... or set = ... in your original source code.
It is a somewhat common convention in Python to avoid naming conflicts with reserved words (list, set, or, if, with, while, etc...) by appending an underscore to the name. In this case, that would mean writing either list_ = ... or set_ = .... A good coding practice in general though would be to come up with a specific name for your variable that describes it exactly. For example, you might use used_spell_list instead of list (just guessing...I have no idea how this was overwritten).
I would like to except the error the following code produces, but I don't know how.
from datetime import datetime
try:
date = datetime(2009, 12a, 31)
except:
print "error"
The code above is not printing "error". That's what I would like to be able to do.
edit: The reason I would like to check for syntax errors, is because 12a is a command line parameter.
Thanks.
command-line "parameters" are strings. if your code is:
datetime(2009, '12a', 31)
it won't produce SyntaxError. It raises TypeError.
All command-line parameters are needed to be cleaned up first, before use in your code. for example like this:
month = '12'
try:
month = int(month)
except ValueError:
print('bad argument for month')
raise
else:
if not 1<= month <= 12:
raise ValueError('month should be between 1 to 12')
You can't catch syntax errors because the source must be valid before it can be executed. I am not quite sure, why you can't simple fix the syntax error, but if the line with the datetime is generated automatically from user input (?) and you must be able to catch those errors, you might try:
try:
date = eval('datetime(2009, 12a, 31)')
except SyntaxError:
print 'error'
But that's still a horrible solution. Maybe you can tell us why you have to catch such syntax errors.
If you want to check command-line parameters, you could also use argparse or optparse, they will handle the syntax check for you.