在Python中“初始化”变量?


问题内容

即使没有必要在python中初始化变量,我的教授仍然希望我们将其用于实践。我编写了程序,但运行良好,但是尝试初始化一些变量后,尝试运行该程序时收到错误消息。这是我程序的第一部分:

def main():

    grade_1, grade_2, grade_3, average = 0.0
    year = 0

    fName, lName, ID, converted_ID = ""
    infile = open("studentinfo.txt", "r")
    data = infile.read()
    fName, lName, ID, year = data.split(",")
    year = int(year)

    # Prompt the user for three test scores

    grades = eval(input("Enter the three test scores separated by a comma: "))

    # Create a username

    uName = (lName[:4] + fName[:2] + str(year)).lower()
    converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
    grade_1, grade_2, grade_3 = grades

错误信息:

grade_1, grade_2, grade_3, average = 0.0

TypeError: 'float' object is not iterable

问题答案:

问题出线了-

grade_1, grade_2, grade_3, average = 0.0

fName, lName, ID, converted_ID = ""

在python中,如果赋值运算符的左侧有多个变量,则python会尝试对右侧进行多次迭代,然后将每个迭代值依次分配给每个变量。变量grade_1, grade_2, grade_3, average需要三个0.0值来分配给每个变量。

您可能需要类似-

grade_1, grade_2, grade_3, average = [0.0 for _ in range(4)]
fName, lName, ID, converted_ID = ["" for _ in range(4)]