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')
Coolq B
  • 344
  • 5
  • 10
  • 1
    Please provide an [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – U13-Forward Jul 04 '18 at 04:19
  • 1
    There's the `try...except...` and there's the `.isdigit()` check for checking if a str is a valid integer – Taku Jul 04 '18 at 04: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. – Mateen Ulhaq Jul 04 '18 at 04: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. – Klaus D. Jul 04 '18 at 04:37

3 Answers3

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.

cdarke
  • 42,728
  • 8
  • 80
  • 84
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.

cdarke
  • 42,728
  • 8
  • 80
  • 84
Coolq B
  • 344
  • 5
  • 10
  • 2
    *why* do you recommend this approach? Generally, in Python, [the opposite is considered more typical](https://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python) – juanpa.arrivillaga Jul 04 '18 at 05:45
  • What do you think `int(result)` on its own does? – cdarke Jul 04 '18 at 05:46
  • @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? – Coolq B Jul 04 '18 at 09:15
  • @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 – Coolq B Jul 04 '18 at 09:18
  • 1
    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. – cdarke Jul 04 '18 at 09:38
  • @cdarke That's a very good point, I guess I was just trying to do one thing at a time, but as you say it is good practice to make sure I cover all errors :) – Coolq B Jul 06 '18 at 14:01
-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')
hsnsd
  • 1,728
  • 12
  • 30
  • 1
    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 Jul 04 '18 at 05:43
  • @cdarke my bad, edited. Can you explain why is a bare except dangerous? – hsnsd Jul 04 '18 at 06:36
  • 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. – cdarke Jul 04 '18 at 06:49