0

I have been trying to find out ways to check about variable types or while do statements but I got confused and didn't know what's going on, on my code. I want to check if end is an integer so I made up my mind with this. Thanks a lot!!

checked=0
while (checked==0):
    end=input('Give me an integer number!')
    if  isinstance(end,(int)):
        checked=1
    else:
        checked=0
        print('This is not an integer!')
ThanosA
  • 1
  • 1

2 Answers2

1

According to the Python motto "Easier to ask for forgiveness than permission" , you could do the following:

while True:
  try:
    end = int(input("Enter an integer"))
    break
  except ValueError:
    print("that's no integer")

If the conversion to int fails, the break is skipped and execution continues in the except ValueError handler. If the conversion is successful, the break exits the loop and you can be sure that end is an integer.

Jasper
  • 3,939
  • 1
  • 18
  • 35
  • What I can't understand, though I found many topics with while True, is the way this loop continues. It continues each time end is not an integer? – ThanosA Jan 18 '15 at 21:00
  • It continues forever, *unless* it succeeds (because it then `break`s out of the loop). – L3viathan Jan 18 '15 at 21:00
  • the `break` terminates it after a successful converstion of the input to `int`. If the conversion fails, the `break` is skipped. – Jasper Jan 18 '15 at 21:01
  • I get the following error now after having copied the above code: ...except value error: SyntaxError :Invalid Syntax – ThanosA Jan 18 '15 at 21:04
  • There must have been edited to ValueError from Value Error – ThanosA Jan 18 '15 at 21:05
  • Yes but what happens if end is not integer for example wouldn't it hit an error message because of end=int(...)? – ThanosA Jan 18 '15 at 21:07
  • No, that's excatly what exceptions are made for. You `try` something that can go wrong. This code is executed `except` some error occurs. https://docs.python.org/2/tutorial/errors.html – Jasper Jan 18 '15 at 21:11
0

User input will always be a string unless casted. Use a try/except block.

try:
    entry = int(input('Enter a integer: '))

except:
    print('That's not an integer.')
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70