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.