I am trying to add a piece of code to this string to check for a negative number in the first position. If the code identifies a negative number it should return "False". I'm having trouble with int and str at the user input command.
def is_number(S):
#if s < 0:
#print("False")
#else:
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
s = input()
is_number(s)
The above code should accept numeric and alpha inputs without throwing an error.
Is this what you want?
def check_negative(s):
try:
f = float(s)
if (f < 0):
return True
# Otherwise return false
return False
except ValueError:
return False
Not entirely sure if this is what you want though, maybe you should see ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000's answer
You can replace your is_number
function with this code:
def is_number(s):
return str(s)[0] == '-' and len(str(s)) > 1
It is a function which checks whether the first character is a negative sign, and if it is, it will return true. Otherwise, the number cannot be negative, and it will then return false. However, if there is only a -
sign, then it is neither and will return false. It only uses one line and is much simpler. It works for strings and floats too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With