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 
1
  • If you use "input", it will always give out "string" representation irrespective of the data type you enter Commented Mar 18, 2016 at 21:58

1 Answer 1

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.

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

1 Comment

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.