0
num=float(raw_input('Enter a number: '))
if num <0:
    print "-"
elif num>0:
    print "+"
else:
    print "0"

this is a simple example from one book. It works fine, but I have a question, how to make that this program would see that I'm entering a letter instead of a number? It works just fine if I'm using numbers, but if I'm entering a letter, the program crashes. I understand that when a program gets a raw input, it needs to check if it is a number or another symbol, but I just don't know what the simplest solution would be?

0

3 Answers 3

0
num=raw_input('Enter a number: ')
if num is float:
    num = float(num)
    if num <0:
        print "-"
    elif num>0:
        print "+"
    else:
        print "0"
else:
    #do something

use 'is' to judge whether input value is float or not

Sign up to request clarification or add additional context in comments.

Comments

0

Method 1:


Try to check if input is a number. This will work for both negative and positive numbers, but not for numbers like 1.1, 1.2, etc:

try:
   val = int(userInput)
   #code here
except ValueError:
   print("That's not an int!")

Method 2:


Using an if-statement alone you could use the isdigit() function. However, this will not work for negative numbers as for example -1 will return False.

if userInput.isdigit():
    #your code here
else:
    Print("Not a digit")

Method 3:


Here is another method to check if given string is a number:

import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
    print("Given string is number")
else:
    print("Given string is not a number")

Also, try to include a log with the error next time, and add some more tags for visibility like integer, string and if-statement. :)


Source: How to check if string input is a number?

Comments

-2

Use some simple string methods like below:

>>> s = '1234'
>>> s.isdigit()
True
>>>s = 'abd'
>>> s.isdigit()
False
>>> s = 'abc123'
>>> s.isdigit()
False

2 Comments

How about '12.345'.isdigit()?
Yeah! Obviously it gives False.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.