Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Try except problem
#1
Hi,
I'm currently coding a DNA to RNA translator and I'd like to make some exceptions with the try and except key.
The first exception I'm doing is if in the phrase the user inputs there aren't the letters I stated, it should notify an error. However, it's not doing that.

Here's the code
try:
    def translate(phrase):
        translation = ""
        for letter in phrase:
            if letter.lower() in "a":
                if letter.isupper:
                    translation = translation + "U"
                else:
                    translation = translation + "u"
            elif letter.lower() in "t":
                if letter.isupper:
                    translation = translation + "A"
                else:
                    translation = translation + "a"
            elif letter.lower() in "c":
                if letter.isupper:
                    translation = translation + "G"
                else:
                    translation = translation + "g"
            elif letter.lower() in "g":
                if letter.isupper:
                    translation = translation + "C"
                else:
                    translation = translation + "c"
        return translation


except SyntaxError:
    def translate(phrase):
        for letter in phrase:
            if letter.lower() in "bdefhijklmnopqrsvwxyz":
                print("DNA CHAIN INCORRECT")


print(translate(input("Enter your DNA chain:")))
Reply
#2
You use try and except to capture an exception generated while your code is run. You want to do the opposite. You want to raise an exception when your code identifies an error with the argument value.
if not letter in 'aAcCgGuU':
    raise ValueError('Invalid character in DNA chain')
I think ValueError is a better fit since the problem is that an invalid value was provided. SyntaxError is really for problems in parsing Python.

https://docs.python.org/3/c-api/exceptions.html
Reply
#3
Ok, I’ll do that.
Once my code works, will it be able to run in a framework like django.

Thanks for the help
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020