简体   繁体   中英

Check a float value contains a minus sign (hyphen-minus) - Python

I just want to check the variable contains a negative value but it keeps throwing me this error:

Traceback (most recent call last):
  File "C:\...\...\...\file.py", line 88, in <module>
     main()
  File "C:\...\...\...\file.py", line 33, in main
     if '-' in done:
TypeError: argument of type 'float' is not iterable
[Finished in 0.2s with exit code 1]

I have looked at others with similiar error but none of them gave me the idea to my current problem.

Still new to python and programming not having a good grasp on this. Hopefully you can guide me in the right way. Appreciate your help, folks!

I have done this so far:

def main():
   val = '-96000'

   flo = float(val)

   if '-' in flo:
       print('yes')

if __name__ == '__main__':
   main()

String characters don't exist in float objects. Just perform a numeric comparison:

if flo < 0:
    print('yes')

The keyword in is used to iterate an iterable object such as a str instance, so your logic would work with a string:

if '-' in val:
    print('yes')

Of course, in the second instance it's wiser to compare against the first character or the start of the string, eg val[0] == '-' or val.startswith('-') .

Simply remove the cast from str to float , so you can control the minus sign is present:

def main():
   val = '-96000'

   if '-' in val:
       print('yes')

if __name__ == '__main__':
   main()

Or better, control that the str actually begins with the minus sign:

   if val.startswith('-'):
       print('yes')

Or better, still cast to float, then control the value of your data:

def main():
   val = '-96000'
   flo = float(val)
   if flo < 0:
       print('yes')

if __name__ == '__main__':
   main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM