我知道你已经接受了另一个答案,但我认为更广泛的问题需要解决-适合当前语言的编程风格。
是的,Python中不需要“初始化”,但是您所做的不是
初始化。它只是对其他语言中的初始化的不完全和错误的模仿。在静态类型语言中初始化的重要一点是指定变量的性质。
在Python中,与在其他语言中一样,在使用变量之前,您确实需要给出它们的值。但是,在函数开始时给它们值并不重要,如果你给的值与它们以后收到的值无关,那就错了。这不是“初始化”,而是“重用”。
我将对您的代码做一些注释和更正:def main():
# doc to define the function
# proper Python indentation
# document significant variables, especially inputs and outputs
# grade_1, grade_2, grade_3, average - id these
# year - id this
# fName, lName, ID, converted_ID
infile = open("studentinfo.txt", "r")
# you didn't 'intialize' this variable
data = infile.read()
# nor this
fName, lName, ID, year = data.split(",")
# this will produce an error if the file does not have the right number of strings
# 'year' is now a string, even though you 'initialized' it as 0
year = int(year)
# now 'year' is an integer
# a language that requires initialization would have raised an error
# over this switch in type of this variable.
# Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a comma: "))
# 'eval' ouch!
# you could have handled the input just like you did the file input.
grade_1, grade_2, grade_3 = grades
# this would work only if the user gave you an 'iterable' with 3 values
# eval() doesn't ensure that it is an iterable
# and it does not ensure that the values are numbers.
# What would happen with this user input: "'one','two','three',4"?
# Create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
# earlier you 'initialized' converted_ID
# initialization in a static typed language would have caught this typo
# pseudo-initialization in Python does not catch typos
....