7

I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't recognize it as a number when "-" is included.

This is what I have so far:

def contestTest(): # Neutral point for struggle/tug of war/contest x = 0 while -5 < x < 5: print "Type desired amount of damage." print x choice = raw_input("> ") if choice.isdigit(): y = int(choice) x += y else: print "Invalid input." if -5 >= x: print "x is low. Loss." print x elif 5 <= x: print "x is high. Win." print x else: print "Something went wrong." print x 

The only solution I can think of is some separate, convoluted series of statements that I might squirrel away in a separate function to make it look nicer.

1

7 Answers 7

15

You can easily remove the characters from the left first, like so:

choice.lstrip('-+').isdigit() 

However it would probably be better to handle exceptions from invalid input instead:

print x while True: choice = raw_input("> ") try: y = int(choice) break except ValueError: print "Invalid input." x += y 
Sign up to request clarification or add additional context in comments.

1 Comment

maybe it is better: choice.lstrip('-+').isnumeric()
3

Instead of checking if you can convert the input to a number you can just try the conversion and do something else if it fails:

choice = raw_input("> ") try: y = int(choice) x += y except ValueError: print "Invalid input." 

Comments

1

You can solve this by using float(str). float should return an ValueError if it's not a number. If you're only dealing with integers you can use int(str).

So instead of doing

if choise.isdigit(): #operation else: #operation 

you can try

try: x = float(raw_input) except ValueError: print ("What you entered is not a number") 

I haven't tested if replacing float with int works.

I saw this on Python's documentation as well (2.7.11) here.

Comments

1

If you just want integers and reject decimal numbers, you can use the following function to check.

def isInteger(string): if string[0] == '-': #if a negative number return string[1:].isdigit() else: return string.isdigit() 

Comments

0

You may use a regular expressions to check if the string has the pattern of an integer number before attempting any casting:

import re patternInteger = re.compile("^[+-]?[0-9]+$") if patternInteger.match(string): return int(string) else: return "This string is not an integer number" 

You can generalize your regex pattern to match other kind of strings that may look like floating point numbers or even complex numbers. In this situation regex might be a bit overkill but can be very useful to learn if in the future you have to deal with a more general pattern to recognise.

Comments

0

This may be simpler:

def is_negative_int(value: str) -> bool: if value == "": return False is_positive_integer: bool = value.isdigit() if is_positive_integer: return True else: is_negative_integer: bool = value.startswith("-") and value[1:].isdigit() is_integer: bool = is_positive_integer or is_negative_integer return is_integer 

References:

Comments

-1
a = "-1" def is_number(string:str): if string.isdigit(): return f'число = {string.isdigit()}' elif string[0] == '-': if string[1:].isdigit(): return f'отрицательное число = {int(string[1:]) * -1}' else: return f'Ввели не число' print(f"Итоги: {is_number(a)}") 

1 Comment

Please translate all text to English

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.