When I type in 23.3 and 44 it outputs only one of these values is a valid number And a Valid number basically is any number that has no strings how can I fix this where 23.3 and 44 outputs both are values
x = input(":")
y = input(":")
if x.isnumeric() and y.isnumeric():
print('both are valid numbers')
elif x.isnumeric() or y.isnumeric():
print('one of the values is a valid number ')
else: print('none are valid numbers')
CodePudding user response:
The isnumeric
method does not return True for the decimal separator.
CodePudding user response:
isnumeric()
only checks whether the value is an integer, but not if it is a float.
Unfortunately, I haven't found a very clean way to handle this. I think the best solution is to implement your own function, maybe something like this:
def is_decimal(s):
try:
float(s)
except ValueError:
return False
else:
return True
x = input(":")
y = input(":")
if is_decimal(x) and is_decimal(y):
print('both are valid numbers')
elif is_decimal(x) or is_decimal(y):
print('one of the values is a valid number ')
else: print('none are valid numbers')
CodePudding user response:
def is_number(s):
if s.count(".")==1:
if s[0]=="-":
s=s[1:]
if s[0]==".":
return False
s=s.replace(".","")
for i in s:
if i not in "0123456789":
return False
else:
return True
elif s.count(".")==0:
if s[0]=="-":
s=s[1:]
for i in s:
if i not in "0123456789":
return False
else:
return True
else:
return False
x = input(":") y = input(":") if is_number(x) and is_number(y): print('both are valid numbers') elif is_number(x) or is_number(y): print('one of the values is a valid number ') else: print('none are valid numbers')
CodePudding user response:
You can try this:
def check_user_input(input_val):
try:
# Convert it into integer
val = int(input_val)
return True
except ValueError:
try:
# Convert it into float
val = float(input_val)
return True
except ValueError:
return False
x = input(":")
y = input(":")
x_is_number = check_user_input(x)
y_is_number = check_user_input(y)
if x_is_number and y_is_number:
print('both are valid numbers')
elif x_is_number or y_is_number:
print('one of the values is a valid number ')
else: print('none are valid numbers')
Input and Output:
:23.5
:44
both are valid numbers
:23.5
:a
one of the values is a valid number
:a
:b
none are valid numbers
CodePudding user response:
This is the description of str.isnumeric in the documentation.
Return True if there is at least one character in the string and all characters are numeric characters, False otherwise.
So it can't determine float directly.
You can use a regular expression to determine whether it is a float.
import re
regex = re.compile(r"^\d (?:\.\d )?$")
x = input(":")
y = input(":")
def is_numeric(s: str):
return s.isnumeric() or regex.match(s)
x_is_numeric = is_numeric(x)
y_is_numeric = is_numeric(y)
if x_is_numeric and y_is_numeric:
print('both are valid numbers')
elif x_is_numeric or y_is_numeric:
print('one of the values is a valid number ')
else:
print('none are valid numbers')