+ 1
Is input validation necessary within functions in Python or other languages? If so, why?
I am new to programming so, I don't know about these things.
2 Réponses
+ 1
Don't know how deep you are into the course, I guess you reach the point of error handling?
In python, any user input you obtain from input(), is always a string.
If you need that user input to do math calculation, you have to convert it into an int or a float.
Let's say you convert it into an int with this code.
num = input()
num = int(num)
If the user input 'abc', the above code runs into error.
So you can use try...except to handle this situation.
num = input()
try:
num = int(num)
except:
print('Please enter a number')
With this, if the user input a non numerical value, it will print "Please enter a number".
Other languages, for example, Java, has different method to read values without the process of conversion.
0
adding to what Wong Hei Ming said, you can also do this,
num = int(input())
and using except,
try:
num = int(input())
except:
print("Please enter a number")
you can also use specific errors for multiple exceptions for more than one response to them.
try:
num = int(input())
except ValueError:
print("Please enter a number")
or
try:
num = int(input())
except (ValueError):
print("Please enter a number")
and
try:
num = int(input())
except ValueError:
print("Please enter a number")
except ZeroDivisionError:
print("Wait, that's not possible.")