0

When I execute the code below, is there anyway to keep python compiler running the code without error messages popping up?

Since I don't know how to differentiate integers and strings,
when int(result) executes and result contains letters, it spits out an error message that stops the program.

Is there anyway around this?

Here is my code:

result = input('Type in your number,type y when finished.\n')
int(result)
if isinstance(result,str):
    print('finished')
4
  • 1
    Please provide an Minimal, Complete, and Verifiable example Commented Jul 4, 2018 at 4:19
  • 1
    There's the try...except... and there's the .isdigit() check for checking if a str is a valid integer Commented Jul 4, 2018 at 4:31
  • You shouldn't fight the language. Consider what the return value of invalid operations should be. None? Should this None then propagate through everything it touches? If you really want stuff like this, I suppose you could look into a functional programming language which makes it easier to pass through "invalid" results (e.g. using Maybe monad). Doing this in python sounds like a pain. Commented Jul 4, 2018 at 4:33
  • Python is a strongly type language and knows the difference between numbers and letters very well. Except of cause numbers are presented as strings. And BTW Python is not a compiled language. It generates bytecode but is interpreted at runtime. Commented Jul 4, 2018 at 4:37

3 Answers 3

4

Let's look at your code:

int(result)

All that will do is raise an exception if result cannot be converted to an int. It does not change result. Why not? Because in python string (and int) objects cannot be changed, they are immutable. So:

if isinstance(result,str):
    print('finished')

this test is pointless, because result will always be a str because you have not changed it - that's the type returned by input().

The way to deal with error messages is to fix or handle them. There are two general approaches, "look before you leap" and "exception handling". In "look before you leap" you would check to see if result can be turned into an int by using a string test like str.isdigit(). In python the usual way is to use exception handling, for example:

result = input('Type in your number,type y when finished.\n')

try:
    # convert result to an int - not sure if this is what you want
    result = int(result)
except ValueError:
    print("result is not an int")

if isinstance(result, int):
    print("result is an int")

You can see I specifically tested for ValueError. If you don't have this and just have except then it would trap any error, which could mask other issues.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a great answer! I hope the OP considers this solution.
0

Actually, with Python and many other languages, you can differentiate types.

When you execute int(result), the int builtin assumes the parameter value is able to be turned into an integer. If not, say the string is abc123, it can not turn that string into an integer and will raise an exception.

An easy way around this is to check first with one of the many builtins isdigit(), before we evaluate int(result).

# We assume result is always a string, and therefore always has the method `.isdigit`
if result.isdigit():
    int(result)
else:
    # Choose what happens if it is not of the correct type. Remove this statement if nothing.
    pass

Note that .isdigit() will only work on whole numbers, 10.4 will be seen as not an integer. However 10 will be.

I recommend this approach over try and except clauses, however that is a valid solution too.

6 Comments

why do you recommend this approach? Generally, in Python, the opposite is considered more typical
What do you think int(result) on its own does?
@juanpa.arrivillaga Whilst the opposite is typical, as cdarke says in the comment below, a bare except is dangerous for numerous reasons. However I do not expect newcomers to Python to fully understand the exception model. Hence, why I recommend users don't use them until they have learnt what it actually does to prevent programming errors in the future. Should I include this in my answer?
@cdarke int(result) is in place because since the switch from Python 2 to Python 3, there were a few changes, one such change was to change input() to no longer automatically evaluate the input type, and instead return a string result. So it is necessary to first convert result into an integer before the OP can presumably interact with result as an integer (say adding or subtracting it). Though I do understand that int(result) doesn't actually change the result variable, only evaluates it, I just didn't take it upon me to answer that too, I only wanted to solve the question at hand
My point was that you posted code that did not "work". Surely we have a responsibility to point out glaring mistakes? Your point about python 2 use of input() is valid, it had not occurred to me that the OP might have been reading an old book or web posting.
|
-2

You can put everything that might throw an error, in a try block, and have an except block that keeps the flow of the program.

btw I think, in your code it should be, isinstance(result,int) not isinstance(result,str)

In your case,

result = input('Type in your number,type y when finished.\n')
try:
    result = int(result)
except:
    pass
if isinstance(result,int):
    print('finished')

3 Comments

Did you actually try this code? For a start the continue is invalid outside a loop. Second, a bare except is dangerous and should not be generally used. Third: int(result) does not change result, result will stay a string and it will never print "finished".
@cdarke my bad, edited. Can you explain why is a bare except dangerous?
A bare except is dangerous because it will trap any error which can mask a genuine error. For example, if you mis-typed int(result) as int(ressult) then you should get a NameError, but with a bare except it will ignore this typo and carry on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.