0

Sorry I'm a beginner. But like if I had:

x = eval(input('Enter a value for x: '))

How do I make it so that if the person input a string instead of a number it would print "Enter a number" instead of getting an error. Some type of if statement where:

if x == str():
    print('Please enter a number')

else:
    print('blah blah blah')
kat
  • 1
  • better close targets would have been: [How do I check if a string is a number in Python?](http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-in-python) or [How do you check if a string contains ONLY numbers - python](http://stackoverflow.com/questions/21388541/how-do-you-check-if-a-string-contains-only-numbers-python) – bummi Oct 11 '14 at 22:30

1 Answers1

0

It sounds like you are looking for str.isdigit:

>>> x = input(':')
:abcd
>>> x.isdigit()  # Returns False because x contains non-digit characters
False
>>> x= input(':')
:123
>>> x.isdigit()  # Returns True because x contains only digits
True
>>>

In your code, it would be:

if not x.isdigit():
    print('Please enter a number')  
else:
    print('blah blah blah')

On a side note, you should avoid using eval(input(...)) because it can be used to execute arbitrary expressions. In other words, it is very often a security hole and is therefore considered a bad practice by most Python programmers. Reference:

Is using eval in Python a bad practice?

Community
  • 1
  • 1