Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old November 6th, 2012, 09:27 PM
Brewzer Brewzer is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 9 Brewzer User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 h 55 m 30 sec
Reputation 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

Reply With Quote
  #2  
Old November 7th, 2012, 08:28 AM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,357 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 9 m 51 sec
Reputation Power: 383
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!

Reply With Quote
  #3  
Old November 7th, 2012, 09:39 AM
Brewzer Brewzer is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 9 Brewzer User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 h 55 m 30 sec
Reputation 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

Reply With Quote
  #4  
Old November 7th, 2012, 10:09 AM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,357 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 9 m 51 sec
Reputation Power: 383
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 08:36 PM. Reason: flush moved

Reply With Quote
  #5  
Old November 7th, 2012, 01:08 PM
Brewzer Brewzer is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 9 Brewzer User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 h 55 m 30 sec
Reputation 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

Reply With Quote
  #6  
Old November 7th, 2012, 03:08 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,357 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 9 m 51 sec
Reputation Power: 383
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)

Reply With Quote
  #7  
Old November 7th, 2012, 09:30 PM
Brewzer Brewzer is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 9 Brewzer User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 h 55 m 30 sec
Reputation 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.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Newbie question regarding exceptions

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap