-3

I'm writing a program that prompts for an integer and prints the integer, but if something other than an integer is input, the program keeps asking for an integer.

I can't figure out how to get it to reset properly. I have tried different methods but nothing works.

This is my code so far:

inp = input ("Enter a Integer:")
while inp.isdigit():
    print (inp)
    break
else:
    print ("Enter a Integer")

Does anyone have some suggestions?

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Jacob
  • 7
  • 1
  • 4
  • What isn't working? Do you get an error, unexpected behavior? – Tristan Oct 31 '18 at 19:45
  • I don't want to give the answer straight away. But think like this. Why not putting the test `isdigit` in an if block inside the loop? If it is correct, you break, else it will go again in the loop. – meyer1994 Oct 31 '18 at 19:46
  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Patrick Artner Oct 31 '18 at 19:47

1 Answers1

1

Its better to follow pythons Ask forgiveness not permission stratagem :

while True:
    try:
        k = input("integer:")    # gets a string
        k = int(k)               # tries integer conversion
        break                    # if success: break while True loop
    except ValueError:
        print("Try again.")      # int() failed

print(k)                         # print the output

Output:

integer:a
Try again.
integer:b
Try again.
integer:5
5

Advantage: this works even for negative integers, the isdigit() check does not.

Exceptionhandling: https://docs.python.org/3/tutorial/errors.html#handling-exceptions

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69