#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    9
    Rep Power
    0

    Newbie question regarding exceptions


    Good day,

    I am attempting to write a program that handles exceptions.

    My goal is to write a simple program that instructs the user to enter a series of 3 grades they received on a 3 separate tests. Then add those numbers together and print that sum. In this program I am going to have the user enter a number that represents the letter grade (A=4, B=3, C=2).

    I guess the program would looks something like this:
    Please enter grade on test 1: 3.5
    Please enter grade on test 2: 3
    Please enter grade on test 3: 2.75

    If the user mistakenly enters a letter I want it to error and request them to reenter the value. After the 2nd failed attempt I want it to state that there are 2 errors in a row and the program will quit.

    Any assistance is greatly appreciated.

    Regards
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,997
    Rep Power
    481

    prompt of the day (POTD)


    Code:
    import sys
    
    class IdiotError(Exception):
        pass
    
    def prompt(PS1='? ',conversion=str,tries=2,default=None,
               inf=sys.stdin,ouf=sys.stdout,raiseException=False):
        ouf.write(PS1)
        for i in range(tries):
            S = inf.readline()
            if S[-1] == u'\n':
                S = S[:-1]
            try:
                return conversion(S)
            except:
                pass
            ouf.write('Please enter a %s: '%str(conversion))
        if raiseException and (None == default):
            raise IdiotError('bright user did not comply with clear instruction')
        return default
    
    # tested cases.  Doesn't work as a doctest.
    #>>> import io
    #>>> I=io.StringIO
    #>>> prompt(conversion=int,inf=I(u'3'))
    #? 3
    #>>> print(prompt(conversion=int,inf=I(u'3\n;laskjde\n\n\n')))
    #? 3
    #>>> a=prompt(conversion=int,inf=I(u'3\n;laskjde\n\n\n'))
    #? >>> print(a)
    #3
    #>>> a = prompt(conversion=int,inf=I(u'erk\nbleck\n3\n'),default=666)
    #? Please enter a <type 'int'>: Please enter a <type 'int'>: >>> print(a)
    #666
    #>>> a = prompt(PS1='ENTER AN INTEGER',conversion=int,inf=I(u'erk\nbleck\n3\n'),tries=1)
    #ENTER AN INTEGERPlease enter a <type 'int'>: >>> print(a)
    #None
    #>>> a = prompt(PS1='ENTER AN INTEGER',conversion=int,inf=I(u'erk\nbleck\n3\n'),tries=1,raiseException=True)
    #ENTER AN INTEGERPlease enter a <type 'int'>: Traceback (most recent call last):
    #  File "<stdin>", line 1, in <module>
    #  File "p.py", line 24, in prompt
    #    raise IdiotError('bright user did not comply with clear instruction')
    #p.IdiotError: bright user did not comply with clear instruction
    #>>> a = prompt(PS1='ENTER AN INTEGER',conversion=int,inf=io.StringIO(u'0\nerk\nbleck\n3\n'),tries=1)
    #ENTER AN INTEGER>>> print(a)
    #0
    #>>>
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    9
    Rep Power
    0
    b49P23TIvg,

    Thanks for your reply. I copied the code you supplied below and I get a invalid syntax error at line 11.

    I am very new to python and programming in general. I am using python 3.2.3 so not sure if that is an issue.

    Thanks
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,997
    Rep Power
    481
    Hmm, I thought that program would work in either version. Must have not tested python3.

    Example of code this post with both python versions with the benefit that I've shown an example of how code can be tested for syntax error:
    Code:
    $ python3 -ic 'import p'
    >>> p.prompt()
    ? the
    'the'
    >>> 
    $ 
    $ 
    $ python -ic 'import p'
    >>> p.prompt()
    ? the
    'the'
    >>>

    Code:
    import sys
    
    class IdiotError(Exception):
        pass
    
    try:
        newline = eval(r"u'\n'")
    except SyntaxError:
        newline = '\n'
    
    def prompt(PS1='? ',conversion=str,tries=2,default=None,
               inf=sys.stdin,ouf=sys.stdout,raiseException=False):
        ouf.write(PS1)
        for i in range(tries):
            ouf.flush()
            S = inf.readline()
            if S[-1] == newline:
                S = S[:-1]
            try:
                return conversion(S)
            except:
                pass
            ouf.write('Please enter a %s: '%str(conversion))
        if raiseException and (None == default):
            raise IdiotError('bright user did not comply with clear instruction')
        return default
    Last edited by b49P23TIvg; November 7th, 2012 at 09:36 PM. Reason: flush moved
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    9
    Rep Power
    0
    I have to admit that the code you enterered is way over my head.

    I coded in the following the best I could and it sort of works, below is what I want to get working.

    I cant get the following working:
    1. I want to add the 3 numbers together
    2. I want the except statment to require a number. If after the 2nd entry the user does not enter a number I want the program to fail. this should be the case for all 3 entries.

    Code:
    try:
        firstnum = int(input("Enter 1st number : "))
    
    except ValueError:
        print('Value must be a valid integer, please re-enter number')
    
    try:
        secondnum = int(input("Enter 2nd number : "))
    
    except ValueError:
        print('Value must be a valid integer, please re-enter number')
    
    try:
        thirdnum = int(input("enter 3rd number : "))
    
    except ValueError:
        print('Value must be a valid integer, please re-enter number')
        
    sum = firstnum + secondnum + thirdnum
    print ('Now the sum of the numbers equals : '), sum
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,997
    Rep Power
    481
    Code:
    while True:
        try:
            firstnum = int(input("Enter 1st number : "))
        except ValueError:
            print('Value must be a valid integer, please re-enter number')
        else:
            break
    Please figure out how to use lists and functions. Duplicate code is a nightmare. You'll see that you now have to make the same changes in your program 3 times.

    "sum" already has a python meaning. Hiding the builtin name is a bad idea.

    You've written a python3 tuple that won't do what you hope.
    # won't print sum
    print ('Now the sum of the numbers equals : '), sum

    # will print sum
    print ('Now the sum of the numbers equals : ', sum)
    [code]Code tags[/code] are essential for python code and Makefiles!
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    9
    Rep Power
    0
    Thanks for your help; I am trying to get familiar with the language in preparation for my first programming class which starts in January.

IMN logo majestic logo threadwatch logo seochat tools logo