0

I wrote this code

def is_integer():
    inp = input("Insert an integer ")
    try:
        inp = int(inp),
        print("Ok!")
    except:
        print("It's not a integer"),
        print(is_integer())

print(is_integer())

Tt works when I insert a type that is not-commutable as integer, when I try to insert a number I get those None.

Insert an integer 3
Ok!
None
None

Moreover I would like to ask if there's a way to obtain the same result using an "if statement" instead of a "try/except" one.

Thank you in advance

Rafid Aslam
  • 187
  • 1
  • 9
Gonake
  • 5
  • 2
  • Functions return `None` if you don't return anything. – Mateen Ulhaq Jan 06 '21 at 23:30
  • 2
    ...And I don't see `return` anywhere! – Mateen Ulhaq Jan 06 '21 at 23:30
  • See [return, return None, and no return at all?](https://stackoverflow.com/questions/15300550/return-return-none-and-no-return-at-all/53091273) and [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – G. Anderson Jan 06 '21 at 23:31
  • Use `return`. If you don't use it, python will not see any output, only print functions. It will return `None`. –  Jan 06 '21 at 23:42

3 Answers3

1

You need to use return instead of print.

This is how you could write it.

def is_integer():
    inp = input("Insert an integer ")
    try:
        inp = int(inp)
        return("Ok!")
    except:
        return("It's not a integer")

print(is_integer())
BeeFriedman
  • 1,501
  • 1
  • 5
  • 24
1

Instead of using print(), use the return function. The return function is a very known and essential part of python. Also, you don't have to use the commas.

def is_integer():
    Int = input('Insert an integer: ')
    try:
        Int = int(Int)
        return True
    except:
        return False

Now try printing.

0

This troubles me when I first learned python.

print and return

Essentially, print only literally print out the content to the terminal, while return means the content will be held/stored, which allows you to reuse your function later.

By default for each python function, if there is no explicit return statement, python will add a return None to the function. That means in your code example, the function will return None.

For the last line print(is_integer()), this will print out the return value of your function, which is None. You can examine it by removing all print() functions inside.

try/except

Why you have to use try/except here? If you replace with if/else statement, the int() function will throw an error/exception when your input is not a data which can be transferred to an integer, for example a string like a.

try/except helps you to catch an error, when there is an error occuring in the try block, the program will skip the try block and jump to except block.

As you can see, if statement will only run the int() method in a premise that the input is able to be transferred into an integer. try also run int(), but it can handle the case when your input is not valid by adding another except block.

This means try/except will make your program more robust and will not easily stop due to some errors or exceptions.

Is that possible to use if/else to replace?

The answer is yes, but not recommendable:

def is_integer():
    inp = eval(input("Insert an integer "))
    if type(inp) is int:
        print("valid input")
        return True
    else:
        print("invalid input")
        return False

print(is_integer())

Here the function eval() will evaluate your input automatically into a correct data type. This will lead to trouble in some cases:

In [2]: inp = input('input a string: ')
input a string: int
In [3]: i = eval(inp)
In [4]: i
Out[4]: int
In [5]: type(i)
Out[6]: type

Now you notice that when I take int as my input, the eval function will evaluate my input as a int type, not a int string. Because for python, int is a pre-occupied keyword to represent the data type of integer, and this is the correct answer for python.

As a conclusion, my suggestions are

  • add return to each function explicitly, even when you do not need to return anything, a simple return or return None is doable (as you get more familiar you may stop adding return every time),
  • avoid using an eval function, unless you totally understand and things are under your control,
  • use try/except if there is a premise to clear in your conditions, which will make your code much more robust.
convers39
  • 237
  • 4
  • 9
  • The problem is solved and your explanation is useful! Thank you so much – Gonake Jan 07 '21 at 11:25
  • You are welcome. BTW there is an another way to check if input is an integer by using `str.isdigit()` method, for example `if inp.isdigit(): ... else: ...`. `isdigit` returns a `boolean` so will match better in this case. – convers39 Jan 09 '21 at 13:33