By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,768 Members | 2,054 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,768 IT Pros & Developers. It's quick & easy.

How to create my own exception for brackets?

P: 3
i want to create my own exception with code saying whether or not someone has entered a ) after a (, for example (jdduu) is ok, but hkbvbhb)hkhb(, is not, how would i start
Dec 3 '10 #1
Share this Question
Share on Google+
4 Replies

Expert Mod 2.5K+
P: 2,851
First you would create an algorithm to determine if the user entered unbalanced parentheses. You don't really need a user-defined exception. Just raise an exception based on a certain condition. But if you want to:
Expand|Select|Wrap|Line Numbers
  1. class UnbalancedParenthesesError(Exception):
  2.     pass
  4. class NoParenthesesError(Exception):
  5.     pass
  7. def getinput(prompt="Enter input enclosed by parentheses"):
  8.     s = raw_input(prompt)
  9.     i = s.find("(")
  10.     j = s.find(")")
  11.     if i < 0 or j < 0:
  12.         raise NoParenthesesError("You left off the parentheses")
  13.     elif j < i:
  14.         raise UnbalancedParenthesesError("Your parentheses are unbalanced")
  15.     return s
  17. print getinput()
Dec 3 '10 #2

P: 3
this method works for single parentheses for example (hcvhkdb), but not for parentheses within parentheses (jcdbjkbdcjb(238))
Dec 4 '10 #3

Expert Mod 2.5K+
P: 2,851
My example was never intended to be a solution. It was intended to be an example of a user-defined exception.
Dec 4 '10 #4

P: 3
your solution helped alot wit another exception i was working on, but im going to continue to try the brackets, will post if i come up with something
Dec 4 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.