The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Python Programming
|
Newbie question regarding exceptions
Discuss Newbie question regarding exceptions in the Python Programming forum on Dev Shed. Newbie question regarding exceptions Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

November 6th, 2012, 09:27 PM
|
|
Registered User
|
|
Join Date: Nov 2012
Posts: 9
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
|

November 7th, 2012, 08:28 AM
|
 |
Contributing User
|
|
|
|
|
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!
|

November 7th, 2012, 09:39 AM
|
|
Registered User
|
|
Join Date: Nov 2012
Posts: 9
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
|

November 7th, 2012, 10:09 AM
|
 |
Contributing User
|
|
|
|
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
|

November 7th, 2012, 01:08 PM
|
|
Registered User
|
|
Join Date: Nov 2012
Posts: 9
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
|

November 7th, 2012, 03:08 PM
|
 |
Contributing User
|
|
|
|
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)
|

November 7th, 2012, 09:30 PM
|
|
Registered User
|
|
Join Date: Nov 2012
Posts: 9
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.
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|