0

I ran into a problem while I was trying to make an if statement.

Below is my code so far:

while True:
    try:
        Names = int(input("Number of names: "))
    except ValueError:
        print("You didn't put in a number, Try again.")
    finally:
        if Names == #this is where I'm stuck

Is there any way to define an integer, so that the loop breaks when the user puts in a number instead of a string?

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35

2 Answers2

0
while True:
    try:
        Names = int(input("Number of names: "))
    except ValueError:
        print("You didn't put in a number, Try again.")
    else:
        break

# use Names here after the while loop, e.g:
for _ in range(Names):
    name = input("...")

else is not really necessary in this case, this is also fine:

while True:
    try:
        Names = int(input("Number of names: "))
    except ValueError:
        print("You didn't put in a number, Try again.")

    break

As is the other answer by bilke, although it's generally good to reduce the amount of code inside the try block so it's clearer where the exceptions you're handling might come from.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

So close to finding it out on your own! :D

while True:
    try:
        names = int(input("Number of names: "))
        break
    except ValueError:
        print("You didn't put in a number, Try again.")
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
bilke
  • 415
  • 3
  • 6