Python adding an exception (edited) -


this simple program working on learn python because beginner. how add exception if user types other y,y,n,n. have searched everywhere can't seem find exception use? everyone's help.

edit:i adjusted code. thing not working if(welcomestring.strip().lower() != 'n' or 'y'): welcomestring = input('not valid choice\nwould reverse string?(y/n):'). not realize user types in y or n. works other letters though.

edit2: working expected until user types in invalid input second time. first time "not valid choice", second time, program exit out.

    import sys   welcomestring = input('welcome string reverser\nwould reverse string?(y/n)')  if not welcomestring.strip().lower() in ['n','y']:   welcomestring = input('not valid choice\nwould reverse string?(y/n):')  if welcomestring.strip().lower() == 'n':     print("thanks using string reverser")  while welcomestring.strip().lower() == 'y':      mystring = input("what string reverse?:")     reversestring = mystring[::-1]     print (("your reversed string %s") % reversestring)     welcomestring = input("would reverse string(y/n)") 

in case not need exception - exception tends exceptional case prevents program continuing, if can still continue under circumstances due user input or conditions may use warning signal that.

here can check input using number of methods , repeat till able valid input :).

if determined use exceptions:

you can here more details how use exceptions , here how subclass exceptions , make user defined exception

so can 3 things:

1) have assertion - cause assertion error text statement seen error

a = 1 b = 2  assert a==b, "a not equal b" 

an assert typically checking bounds - e.g. assert index >=0 , tends missing critical can use them testing if it's own personal code.

for case can have switch statement / if-else chain / have set operations. @ketouem says above can have list of letters , check or dict (if had more letters such 100 faster).

the python wiki gives general guidelines uses of assert:

places consider putting assertions:

  • checking parameter types, classes, or values
  • checking data structure invariants
  • checking "can't happen" situations (duplicates in list, contradictory state variables.)
  • after calling function, make sure return reasonable

    -- python wiki

2) can use 1 of built in exceptions (look here) , raise 1 of those; e.g.

 if(condition_not_met):      raise valueerror("you did not enter correct option") 

these typically have specific uses in mind though.

3) can numpy , many libraries , create own exceptions (you can use library's such numpy's linalgerror, unless manually catching , rethrowing these have domain specific uses.

to create own exception should subclass exception not baseexception

e.g.

class myinputerror(exception):     def __init__(self, value):         self.value = value     def __str__(self):         return repr(self.value) 

and later call this

if(condition_not_met):     raise myinputerror("wrong input. please try again") 

lastly can use if then's , other control structures , exit - isn't common in python , more common in languages c.

in general trying out , catching errors 1 of more key paradigms in python:

eafp easier ask forgiveness permission. common python coding style assumes existence of valid keys or attributes , catches exceptions if assumption proves false. clean , fast style characterized presence of many try , except statements. technique contrasts lbyl style common many other languages such c.

--python glossary


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -