【问题标题】:Unending While loop in pythonpython中无休止的While循环
【发布时间】:2017-08-29 02:06:48
【问题描述】:

我无法让 getClasses 函数中的 while 循环在它应该结束的时候结束。 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

【问题讨论】:

  • 什么时候结束?什么是 getNum?
  • counter2 &lt;= getNumgetNum()?它不能既是整数又是函数……这段代码可能根本不起作用。
  • 什么是getNum???
  • getNum 函数应该返回一个整数。
  • getNum() 函数返回的值是多少? while 循环迭代 getNum() 次。

标签: python while-loop boolean


【解决方案1】:

第 4 行,你是说这个吗?

if counter2 <= getNum() :
    ...

【讨论】:

    【解决方案2】:

    在 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() 
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 2012-11-20
      • 2014-11-02
      相关资源
      最近更新 更多