我不能让我的while循环在getClasses函数结束时应该结束。 getNum和counter都设置为整数。我也试过做while True
和一个if语句来看看这是否会有所帮助,但这只会给我一个无限循环。我知道这是一个简单的问题,但我无法弄清楚我做错了什么。请帮忙。
def getNum():
while True:
try:
num = int(raw_input("How many classes do you have:\n")) #Asks the user for the number of classes he/she has.
break
except:
print("Input must be a number")
return num
def getGrades(): #Gets the grades from the user
counter2 = 1
global grades
if counter2 <= getNum: #If the 2nd counter is less than or equa to the number of classes...
while True:
try:
grades = int(raw_input("What is the grade for class %s:\n" %counter2)) #Asks the user what their grades are for 'counter' class.
counter2 += 1 #...increase the 2nd counter by 1
break
except:
print("Input must be a number")
return grades
def getClasses(): #Gets the user's classes
counter = 1
getNum()
while counter <= getNum: #If the counter is less than or equal to the number of classes...
classes = str(raw_input("Class %s is what:\n" %counter)) #Asks the user what their 'counter' class is.
subjects[classes] = getGrades()
counter += 1 #...increase the counter by 1
return subjects
答案 0 :(得分:0)
第4行,你的意思是这个?
if counter2 <= getNum() :
...
答案 1 :(得分:0)
在except子句后命名异常。在这种情况下是一个ValueError。
如果在执行try子句期间发生异常,则其余部分 该条款被跳过。然后,如果其类型匹配名为的异常 在except关键字之后,执行except子句,然后执行 在try语句之后继续执行。
源 https://docs.python.org/3/tutorial/errors.html
def getGrades():
while True:
try:
grades = int(input())
break
except ValueError:
print("Please enter digits only")
return grades
getGrades()