I was trying to just add some ifs in the function to complete a task in edube.org, related to taking care of the exception or safe gaurd your problem. Below is my program
import math
def inputValueCheck():
x = input("Enter x: ")
print('1 ',x)
number = True
if x.isnumeric() is False:
print('enter positive digits only')
inputValueCheck()
elif x.isnumeric() is True and int(x) < 0:
print('enter positive digits only')
inputValueCheck()
else:
print('2 ',x)
#return x
print('3 ',x)
return x
x = float(inputValueCheck())
y = math.sqrt(x)
print("The square root of", x, "equals to", y)
1st time Input –
Enter x: aaa,
output
-1 aaa
enter positive digits only
2nd time Input –
Enter x: 12
output
print 1 12
print 2 12
print 3 12
print 3 aaaTraceback (most recent call last): File "main.py", line 21, in
x = float(inputValueCheck()) ValueError: could not convert string to float: ‘aaa’
Why is this behaviour by Python? Why is the old value of x i.e. ‘aaa’ here getting returned every time and causing an exception? Can anyone please explain?
2
Answers
You are trying to run a function that:
Just return the function instead of trying to run it again from within the same function. Also you can avoid the extra if statement by using
or
like this:Also, what is the
Number = True
for?When doing a function without argument, it is more difficult to check the type of x, but if you don’t want to define a function inputValueCheck(x), you can always try to convert the variable to a float with an ‘expect ValueError’ if it does’nt work
I also did’nt understand the usage of ‘number = True’ so I made a script where it is useful :
But there can be many way to do it