在python中“初始化”变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30858392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Initializing" variables in python?
提问by Ovi
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:
尽管不需要在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
The error message:
错误信息:
grade_1, grade_2, grade_3, average = 0.0
TypeError: 'float' object is not iterable
采纳答案by Anand S Kumar
The issue is in the line -
问题在于——
grade_1, grade_2, grade_3, average = 0.0
and
和
fName, lName, ID, converted_ID = ""
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.
在python中,如果赋值运算符的左侧有多个变量,python会尝试多次迭代右侧,并将每个迭代的值依次分配给每个变量。变量grade_1, grade_2, grade_3, average
需要三个0.0
值来分配给每个变量。
You may need something like -
你可能需要这样的东西 -
grade_1, grade_2, grade_3, average = [0.0 for _ in range(4)]
fName, lName, ID, converted_ID = ["" for _ in range(4)]
回答by Ovi
If you want to use the destructuring assignment, you'll need the same number of floats as you have variables:
如果要使用解构赋值,则需要与变量数量相同的浮点数:
grade_1, grade_2, grade_3, average = 0.0, 0.0, 0.0, 0.0
回答by Lyndon White
Python treats comma on the left hand side of equal sign ( =
) as an input splitter,
Very useful for functions that return a tuple.
Python 将等号 ( =
)左侧的逗号视为输入分隔符,对于返回元组的函数非常有用。
e.g,
例如,
x,y = (5,2)
What you want to do is:
你想要做的是:
grade_1 = grade_2 = grade_3 = average = 0.0
though that might not be the most clear way to write it.
虽然这可能不是最清晰的写法。
回答by sobolevn
There are several ways to assign the equal variables.
有几种方法可以分配相等的变量。
The easiest one:
最简单的一种:
grade_1 = grade_2 = grade_3 = average = 0.0
With unpacking:
带开箱:
grade_1, grade_2, grade_3, average = 0.0, 0.0, 0.0, 0.0
With list comprehension and unpacking:
使用列表理解和解包:
>>> grade_1, grade_2, grade_3, average = [0.0 for _ in range(4)]
>>> print(grade_1, grade_2, grade_3, average)
0.0 0.0 0.0 0.0
回答by hspandher
You are asking to initialize four variables using a single float object, which of course is not iterable. You can do -
您要求使用单个浮点对象初始化四个变量,这当然是不可迭代的。你可以做 -
grade_1, grade_2, grade_3, grade_4 = [0.0 for _ in range(4)]
grade_1 = grade_2 = grade_3 = grade_4 = 0.0
grade_1, grade_2, grade_3, grade_4 = [0.0 for _ in range(4)]
grade_1 = grade_2 = grade_3 = grade_4 = 0.0
Unless you want to initialize them with different values of course.
除非你想用不同的值初始化它们。
回答by hpaulj
I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.
我知道您已经接受了另一个答案,但我认为需要解决更广泛的问题 - 适合当前语言的编程风格。
Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.
是的,Python 中不需要“初始化”,但您所做的不是初始化。它只是对其他语言中所实践的初始化的不完整和错误的模仿。静态类型语言中初始化的重要之处在于您指定变量的性质。
In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.
在 Python 中,与在其他语言中一样,您确实需要在使用变量之前为其赋予值。但是在函数开始时给他们值并不重要,如果你给的值与他们后来收到的值无关,甚至是错误的。这不是“初始化”,而是“重用”。
I'll make some notes and corrections to your code:
我将对您的代码做一些注释和更正:
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
....
回答by Unbreakable Host
def grade(inlist):
grade_1, grade_2, grade_3, average =inlist
print (grade_1)
print (grade_2)
mark=[1,2,3,4]
grade(mark)