“初始化"python中的变量? [英] "Initializing" variables in python?

查看:48
本文介绍了“初始化"python中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管不需要在python中初始化变量,但我的教授仍然希望我们这样做以进行练习.我编写了我的程序并且它运行良好,但是在我尝试初始化一些变量后,当我尝试运行它时收到一条错误消息.这是我的程序的第一部分:

Even though initializing variables in python is not necessary, my professor still wants us to do it for practice. I wrote my program and it worked fine, but after I tried to initialize some of the variables I got an error message when I tried to run it. Here is the first part of my program:

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值分配给每个变量.

In python, if the left hand side of the assignment operator has multiple variables, python would try to iterate the right hand side that many times and assign each iterated value to each variable sequentially. The variables grade_1, grade_2, grade_3, average need three 0.0 values to assign to each variable.

您可能需要类似 -

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

这篇关于“初始化"python中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆