0

Hi I am a beginner in python coding! This is my code:

while True:
    try:
        x=raw_input("Please enter a word: ")
        break
    except ValueError:
        print( "Sorry it is not a word. try again")

The main aim of this code is to check the input. If the input is string than OK, but when the input is integer it is an error. My problem is that the code with the format integer too, i dont get the error message. Can you help me where is the mistake?

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
angi
  • 9
  • 3

3 Answers3

0

You could use the .isdigit() method to check if a string contains only number characters, eg.

if x.isdigit():
    raise Exception

There is also .isalpha() method for checking if a string is alphabetic.

JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24
0

For checking purpose , you can use the input() method instead and then decide accordingly.

[iahmad@ijaz001 ~]$ python2.7
Python 2.7.15 (default, May  9 2018, 11:32:33) 
[GCC 7.3.1 20180130 (Red Hat 7.3.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

>>> x=input()
'hi'
>>> type(x)
<type 'str'>

>>> x=input()
10
>>> 
>>> type(x)
<type 'int'>
>>> 

[iahmad@ijaz001 ~]$ python3.6
Python 3.6.5 (default, Apr  4 2018, 15:09:05) 
[GCC 7.3.1 20180130 (Red Hat 7.3.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> x=eval(input())
'hi'
>>> 
>>> type(x)
<class 'str'>

>>> 
>>> x=eval(input())
10
>>> 
>>> type(x)
<class 'int'> 
Ijaz Ahmad
  • 11,198
  • 9
  • 53
  • 73
0

If you only need to raise an exception when the input contains one or more digits then you could try:

x = str(raw_input('Please enter your message: '))

if any( i.isdigit() for i in x ):
     raise Exception("Input contains digits, therefore it is not a word")

However, I assume that you want to also raise an exception when the input is something like "hel$o" -- the special characters also needs to be excluded --. In that case you should try to use some regular expressions.

Daedalus
  • 295
  • 2
  • 17