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?
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.
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.
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? "))