1

I want to create an if statement to check whether the number entered is an int or not. I don't know what to do as I am splitting an input (You enter 3d and a variable with 3 and one with d is made). I want it so that if you enter a letter then it doesn't produce an error message.

Here is the code in Question:

  while directionloop ==0:
    while DAmountLoop==0:
        direction=input('How do you want to move? Your answer should look like this 4u, this moves you up 4: ')
        directiondirection=str(direction[1])
        directionamount=(direction[0])
        if type(directionamount) != int:
            print('You need to enter a number for the amount you want to move')
        elif type(directionamount) == int:
            directionamount=int(direction[0])
            DAmountLoop=1
Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
  • If you use "input", it will always give out "string" representation irrespective of the data type you enter – kmario23 Mar 18 '16 at 21:58

1 Answers1

2

The type of direction will always be str, because input() returns str. Hence, the type of direction[0] is always also str (assuming direction is not empty). For this reason, type(direction[0]) != int will always be True.

However, strings have methods that check their contents. In this case, you can use str.isnumeric():

move = input('How do you want to move? ')
direction = direction[1]
amount = direction[0]
if not amount.isnumeric():
      print('You need to enter a number for the amount')

Also note that this will raise an IndexError if the input is shorter than 2 characters. You might want to make a specific check for that, or maybe use a regular expression to incorporate all of the matching logic.

Also, regarding your loop: see this question for a general recipe for validation of user input.

Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • Thanks, I got it working. I am going to sort some other stuff out in my code then I will look at the validation post you linked, I have about 5 other parts of my code that have validation like what I posted. –  Mar 18 '16 at 22:36