-1
while num_students < 0:
   num_students = int(input("How many students are you entering? "))

How do I get it to repeat the question if nothing is entered by the user (so they just go enter), in python?

Delgan
  • 18,571
  • 11
  • 90
  • 141
Izzy
  • 51
  • 1
  • 1
  • 4

3 Answers3

1

I'd recommend a slightly more general approach, if only to avoid a ValueError if the user enters a string that can't be converted to an int.

while True:
    answer = input("How many ... ")
    try:
        num_students = int(answer)
    except ValueError:
        continue
    if num_students >= 0:
        break

An infinite loop with an explicit break is a common Python idiom used in place of the nonexistent do-while loop.

chepner
  • 497,756
  • 71
  • 530
  • 681
0
num_students = -1

while num_students < 0:
    try:
        num_students = int(input("How many students are you entering? "))
    except:
        print "Please enter an integer greater than or equal to 0"

I would recommend this code. It avoids flow of control statements like "break" and "continue" and will not crash if a string or other invalid input is entered. Avoiding flow of control statements makes a program easier to analyze which is helpful for determining its speed or security.

DowntownDev
  • 842
  • 10
  • 15
-1

You can make it works by adding a condition to the while.

while num_students < 0 and not num_students:
   num_students = int(input("How many students are you entering? "))
Pierre Barre
  • 2,174
  • 1
  • 11
  • 23