2016-04-24 63 views

回答

-1

你可以通過添加一個條件來工作。

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

我建議一個稍微更一般的方法,如果只爲了避免ValueError如果用戶輸入不能被轉換爲int的字符串。

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

具有顯式break無限循環是代替不存在do-while循環使用的公用的Python成語。

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" 

我會推薦這段代碼。它避免了像「break」和「continue」這樣的控制語句的流動,並且如果輸入字符串或其他無效輸入時不會崩潰。避免控制語句的流動使程序更易於分析,這對確定速度或安全性很有幫助。