简体   繁体   中英

if else to raise a ValueError

I am following this:

if else in a list comprehension

but the following small program is generating a syntax error:

def to_rna(dnasequences):
    xlate = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'}
    return ''.join(xlate[sequence] for sequence in dnasequences if sequence in xlate.keys() else raise ValueError)

The else clause is generating the error.

If I remove the else clause it runs, however, I want to raise a ValueError for any input that is NOT a key in my dictionary 'xlate'.

NOTE I am working on the rna-transcription problem from exercism.io.

I pass 5 unit tests but I fail the three unit tests requiring a ValueError for invalid input.

You cannot do this in a comprehension. The conditional expression has the form:

expr if expr else expr

(and, sub-note, it should be used in the beginning of the comprehension)

while raise ExceptionClass is a statement , not an expression. As such, a SyntaxError is raised.

In short, if you do want to use raise , you'll have to resort to a for loop.


Alternately, if you're just very passionate about comprehensions, you could define a function which you can then call in the else clause:

def raiser(exc_type):
    raise exc_type

This is because function calls are expressions. Of course, this is quite ugly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM