Error Testing

S

Scott Novinger

Hello.

I've written a program for my kids to calculate arc length. I want to include some error testing for value types entered that are something other than integer values.

My goal is to make sure that the value entered for the radius is an integer value.

How could I rewrite this code to make sure I accomplish my goal of getting an integer value entered? I know the construct is not correct. I'm just learning how to program.

# Create the variable for radius, "radius".
print('Please enter the circle radius and press ENTER:')
radius = input()

# Check to make sure the entered value is an integer.
if type(radius) != type(int):
print('You must enter an integer value.')
print('Please enter the circle radius and press ENTER:')
radius = input()
else:
print('The radius you entered is: ' + radius)

radius = int(radius)

Thanks for your help. I'm using Python v3.2 for windows.

Scott
 
M

Mark Lawrence

Hello.

I've written a program for my kids to calculate arc length. I want to include some error testing for value types entered that are something other than integer values.

My goal is to make sure that the value entered for the radius is an integer value.

How could I rewrite this code to make sure I accomplish my goal of getting an integer value entered? I know the construct is not correct. I'm just learning how to program.

# Create the variable for radius, "radius".
print('Please enter the circle radius and press ENTER:')
radius = input()

# Check to make sure the entered value is an integer.
if type(radius) != type(int):
print('You must enter an integer value.')
print('Please enter the circle radius and press ENTER:')
radius = input()
else:
print('The radius you entered is: ' + radius)

radius = int(radius)

Thanks for your help. I'm using Python v3.2 for windows.

Scott

Please see the example here
http://docs.python.org/3/tutorial/errors.html#handling-exceptions. If
you want further data feel free to ask, we don't bite :)

--
Roses are red,
Violets are blue,
Most poems rhyme,
But this one doesn't.

Mark Lawrence
 
N

Ned Batchelder

Hello.

I've written a program for my kids to calculate arc length. I want to include some error testing for value types entered that are something other than integer values.

My goal is to make sure that the value entered for the radius is an integer value.

How could I rewrite this code to make sure I accomplish my goal of getting an integer value entered? I know the construct is not correct. I'm just learning how to program.

# Create the variable for radius, "radius".
print('Please enter the circle radius and press ENTER:')
radius = input()

# Check to make sure the entered value is an integer.
if type(radius) != type(int):
print('You must enter an integer value.')
print('Please enter the circle radius and press ENTER:')
radius = input()
else:
print('The radius you entered is: ' + radius)

radius = int(radius)

Thanks for your help. I'm using Python v3.2 for windows.

Scott
Hi Scott, welcome!

This line doesn't do what you want:

if type(radius) != type(int):

for a few reasons: First, radius is the result of input(), so it is
always a string, never an int. Second, "int" itself is already a type,
so type(int) is actually "class" (or something like it), not "int".

What you want is to know whether the string inputted can be properly
converted to an int. In Python, the way to do that is to try converting
it, and be prepared for it to fail:

try:
radius = int(radius)
except ValueError:
print('You must enter an integer value.')

--Ned.
 
R

Roy Smith

Ned Batchelder said:
First, radius is the result of input(), so it is
always a string, never an int.

input() returns ints or floats for values which can be converted to
those. I suspect you're thinking of raw_input()?
 
C

Chris Angelico

# Create the variable for radius, "radius".
print('Please enter the circle radius and press ENTER:')
radius = input()

# Check to make sure the entered value is an integer.
if type(radius) != type(int):
print('You must enter an integer value.')
print('Please enter the circle radius and press ENTER:')
radius = input()
else:
print('The radius you entered is: ' + radius)

radius = int(radius)

Thanks for your help. I'm using Python v3.2 for windows.

In Python 3, the input() function always returns a string. Your type
check is never going to succeed. Also, you're not checking what you
think you're checking; you're actually looking to see if input()
returned a type, because the type of int is type:
<class 'type'>

You might want:

if type(radius) != int:

But that still won't work, because input() will always return a string:
<class 'str'>

You can try all these out in the interactive interpreter (you probably
have IDLE installed, which on Windows is rather nicer to work with
than the default interactive mode).

A better check would be to just try to turn the inputted value into an
integer, and fail if that doesn't work. Again, try this interactively:
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
int("not an integer")
ValueError: invalid literal for int() with base 10: 'not an integer'

With a couple of quick checks, you can easily see what happens if the
conversion fails, and then you can deal with that failure. So
effectively, just drop the whole if: block, go straight to the "radius
= int(radius)" line, and deal with the error there.

ChrisA
 
C

Chris Angelico

input() returns ints or floats for values which can be converted to
those. I suspect you're thinking of raw_input()?

Negative. The OP stated Python 3.2, in which Ned's statement is
correct. :) In Python 2.x, yes, input() will return an int if it
evaluates as one, but in 2.x, I would STRONGLY advise against ever
using non-raw input(). (To be honest, I'd have to say that the
innocuous name 'input' concealing code evaluation is an embarrassment,
and one that I'm very much glad is now removed from the language.)

ChrisA
 
N

Ned Batchelder

input() returns ints or floats for values which can be converted to
those. I suspect you're thinking of raw_input()?
In Python 3, input() returns a string.

--Ned.
 
S

Scott Novinger

Please see the example here

http://docs.python.org/3/tutorial/errors.html#handling-exceptions. If

you want further data feel free to ask, we don't bite :)



--

Roses are red,

Violets are blue,

Most poems rhyme,

But this one doesn't.



Mark Lawrence

Mark/ All,

I read the link on Handling Exceptions. The first bit of code worked for my purposes. I was able to reduce my number of lines of code significantly and my program works! Thank you all for your help solving this problem!

My plan is to create several different programs that perform specific Algebraic operations. My boys are learning Algebra 2 and I thought it might be a fun way to help us all learn Algebra and programming together. Python seems to be a good language for learning how to program.

Thanks again!

Scott
 
C

Chris Angelico

I read the link on Handling Exceptions. The first bit of code worked formy purposes. I was able to reduce my number of lines of code significantlyand my program works! Thank you all for your help solving this problem!

As you get accustomed to exception handling, you'll find that it's a
really clean and easy way to... well, handle exceptional situations :)
Tip: In quick throw-away scripts that are run from the command line,
don't even bother catching most exceptions. Just let 'em happen if
they want to happen... your script will terminate with an error
message, and you can deal with it as a human. That saves you even more
code!
My plan is to create several different programs that perform specific Algebraic operations. My boys are learning Algebra 2 and I thought it might be a fun way to help us all learn Algebra and programming together. Python seems to be a good language for learning how to program.

It is an excellent language for that. It's also a great language for
applications. It may not be the fastest in the world, but all
computers wait at the same speed anyway...

Just one thing: When you post here, please either don't use Google
Groups, or follow the advice here:

https://wiki.python.org/moin/GoogleGroupsPython

Preferably, just avoid GG, as a number of people just filter those
posts out. It's not an indictment of you as a person, but the majority
of GG posts are, quite frankly, very annoying for the reasons set out
in the wiki article.

Hope to see you around more!

ChrisA
 
R

rusi

My plan is to create several different programs that perform specific Algebraic
operations. My boys are learning Algebra 2 and I thought it might be a fun way
to help us all learn Algebra and programming together. Python seems to be a
good language for learning how to program.

If you are a programmer and want to start doing some 'real' math stuff, your approach is fine.

Conversely if you are a mathematician (or at least someone whose math fundamentals are well established) then too to start by getting your hands dirtywith coding up some paper-pen/chalk-blackboard math into a system is a good goal and python is as good a language for this as any.

The system sage http://www.sagemath.org/ does some serious math with pythonas glue.

However if your boys are new to both math and programming, you are doing them a disservice by mixing the two using python.

The problem is that python is an imperative language and uses the '=' sign for assignment. In math of course '=' stands for equality.

Now these two usages of '=' are both center-stage and completely different:
- the math = is by definition symmetric -- we can replace x=y by y=x.Whereas in programming we can never replace x=1 by 1=x
- More significantly and dangerously the programming var=rhs has a timingelement and in fact introduces a basic notion of a 'unit of computation', --the statement -- a notion completely absent from the math something=somethingElse

Now one word or signifier meaning different things -- a pun -- is not necessarily bad. To the extent that we humans have more entities to deal with than ready words its even inevitable. Just yesterday there was a discussion about whether 'python' is a TV comic character or a snake, pike a fish or apoker. I think these are relatively harmless.

However with '=' in math and programming, the two are too different to beequated(!!) and too close to be separated.
Because after the programming statement var = lhs
the math predicate var = lhs is typically true.

But then what happens with something like this? x = x+1
For a programmer this is common daily fare.
For a mathematician its an impossibility.

So I suggest you try it (x=x+1) on your boys.
If they think its ok, youve damaged their mathematical acumen
If not, they've yet to begin programming.
If they can answer to the effect that in some contexts its natural and in some not then of course they are very mature and/or geniuses.

I should mention that John Backus, the creator of the first hi-level language and a Turing award winner, more or less said that the assignment is the single biggest problem why programming languages are in such a mess:
http://www.thocp.net/biographies/papers/backus_turingaward_lecture.pdf

Having said that, I also need to say that most programmers dont agree with that.
The minority that do, would earlier be called 'declarative-devotees'; nowadays the fashionable term is functional programming.
My own rather fringe minority position is that Backus et al are right in denouncing the assignment. However so far the attempts at practically realizing this smack of throwing out the baby with the bathwater.

So for the time being, languages like python remain eminently practical.
Its just that they are not so good for building kids' theoretical foundations -- especially of a mathematical sort.
 
D

David Robinow

You can try all these out in the interactive interpreter (you probably
have IDLE installed, which on Windows is rather nicer to work with
than the default interactive mode).
IDLE is cross-platform. Could you explain why you say "on Windows"?
 
T

Tim Chase

IDLE is cross-platform. Could you explain why you say "on
Windows"?

In my experience, the Win32 Python console lacks readline support
(like my stock Python on the Mac OS X machine I have here), and as
such lacks a lot of the niceties. At least on Win32, there is
recall of previous commands (my Mac lacks even that), but there's no
easy "search for the previous command I typed that contains the
following keyword" (control-R followed by search term), no easy
"insert all matching filenames here" (alt+asterisk), etc.

Idle may not provide all that, but it hopefully provides at least
*some* basic features that the console python.exe lacks.

-tkc
 
T

Terry Reedy

IDLE is cross-platform. Could you explain why you say "on Windows"?

The command line console on *nix is apparently less obnoxious that the
one on Windows. So for people who use an editor other than the Idle
editor, there is less reason to use just the Idle shell.
 
T

Terry Reedy

In my experience, the Win32 Python console lacks readline support
(like my stock Python on the Mac OS X machine I have here), and as
such lacks a lot of the niceties. At least on Win32, there is
recall of previous commands (my Mac lacks even that), but there's no
easy "search for the previous command I typed that contains the
following keyword" (control-R followed by search term), no easy
"insert all matching filenames here" (alt+asterisk), etc.

Idle may not provide all that, but it hopefully provides at least
*some* basic features that the console python.exe lacks.

Command Prompt almost 'religiously' imitates the DOS character
interface. The mouse is mostly ignored; it is not tied to the cursor.
Idle is a normal Windows gui app.

Command Prompt displays a window of k lines of a circular queue of n
lines, which are initialized as blank. The default n=300 is not enough
for a test suite run or many help() outputs. If you find the box on the
3rd tab of properties, n can be increased up to 9999, but if you do, the
scroll bar becomes rather useless, as it scrolls through all n lines.

Idle has a normal expanding buffer, with no extra blank lines added.

CP does not have proper cut and paste. I'll leave out most of the
obnoxious details, but selections are rectangular blocks. This is the
only function for the mouse, and uses a separate mouse cursor. Idle has
normal cut and paste that works like any other Windows app.

Idle can recall previous input two different ways, by cursor or key. One
can use the mouse to select where to edit. CP requires use of arrow keys
to move the cursor around. Idle recall input *statements*. CP recalls
input *lines*. Previous multiline statements have to be recalled a line
at a time. CP was not designed for true multiline commands (as opposed
to long commands that wrap and display as multiple lines).

CP has no menu (other than a few entries when one right-clicks on the
icon in the upper left). There is no way to directly save or print the
buffer.
 
C

Chris Angelico

Idle can recall previous input two different ways, by cursor or key. One can
use the mouse to select where to edit. CP requires use of arrow keys to move
the cursor around. Idle recall input *statements*. CP recalls input *lines*.
Previous multiline statements have to be recalled a line at a time. CP was
not designed for true multiline commands (as opposed to long commands that
wrap and display as multiple lines).

This issue applies also to Linux builds with readline. It's Idle's
primary boast, I think, closely followed by hover help for function
signatures.

ChrisA
 
C

Chris Angelico

The command line console on *nix is apparently less obnoxious that the one
on Windows. So for people who use an editor other than the Idle editor,
there is less reason to use just the Idle shell.

Less obnoxious, more friendly, and way WAY more powerful. As I said in
the other thread, multi-line recall is its biggest lack, but for the
rest, it's quite usable. On Windows, not so much. (Mind you, I'm
accustomed to readline, so if you don't have it, you'll feel more
strongly about Idle.)

ChrisA
 
C

Chris Angelico

The problem is that python is an imperative language and uses the '=' sign for assignment. In math of course '=' stands for equality.

Pascal tried to create a new operator, := to be read "becomes", to
deal with the whole equality-vs-assignment issue. Did it really help
anything? I don't think so. Just syntactic salt. Even the comparison
isn't really mathematical - in maths, "x = y" is a statement of truth,
whereas in programming, it's a question ("is x equal to y").

Teaching maths and programming at once is like teaching any other two
arts at once - there'll be differences to grok as well as similarities
to jump on. I would say that the expression evaluator in (almost) any
modern language is a fairly close parallel to standard mathematical
expressions; yes, abutting tokens is multiplication in algebra, but on
the flip side, we don't use (or need) subscript to make multi-letter
identifiers in code. Programming uses more words and less blackboard
notations (compare abs(x) to |x| for example), but it's expressing
things in fairly similar ways most of the time.

ChrisA
 
N

Ned Deily

Pascal tried to create a new operator, := to be read "becomes", to
deal with the whole equality-vs-assignment issue.

Um, Pascal was just following the lead of ALGOL 60, roughly a decade earlier.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top