【发布时间】:2022-01-13 14:52:23
【问题描述】:
由于变量的值不会在函数内部更改,因此我首先运行了一个列表测试器。事实证明,它们确实附加了函数中提供的新值。这是我尝试过的
def test():
testlist.append(6)
testlist=[3,4]
print(testlist)
test()
print(testlist)
输出:-
[3, 4]
[3, 4, 6]
但是当我在我的实际项目中尝试这个时,它不起作用。 以下是部分代码:-
student_name=[]
roll_number=[]
def student_info()
sn=input("Student Name : ")
student_name.append(sn)
rn=input("Roll no. : ")
roll_number.append(rn)
student_info() 运行次数与有多少学生一样多,这也是一个变量。
每次,列表都会为每个学生附加一个值。稍后将在需要时使用索引号提取所有这些值。但是当我尝试调用列表值时,它始终是列表的第一个值。所以列表没有被追加?
def print_card():
for p in range(0,no_of_classes,1):
for l in range(0,class_strength,1):
print("Student Name:",student_name[l],x*50,"Roll No:",roll_number[l])
(请忽略不必要的复杂格式部分)
#This is the main part of the code.
for j in range (no_of_classes):
class_=input("Class name")
print("Class strength of ",class_)
class_strength=int(input())
for i in range (class_strength):
student_info()
print_card()
这是最小的可重现程序
student_name=[]
roll_number=[]
def student_info():
sn=input("Student Name : ")
student_name.append(sn)
rn=input("Roll no. : ")
roll_number.append(rn)
def print_card():
for p in range(0,no_of_classes,1):
for l in range(0,class_strength,1):
x=' '
print('\n')
print("Student Name:",student_name[l],x*50,"Roll No:",roll_number[l])
no_of_classes=2
class_strength=1
for j in range (0,no_of_classes):
for i in range (0,class_strength):
student_info()
print_card()
卡片是为第一堂课创建的,但对于下一堂课,会出现相同的输出。为什么会这样?
预期输出与实际输出
(比如 2 名学生)
kode skool
Student Name: 1 Roll No: 1
Class: 1 Section: 1
Address 1
1
City: 1 Pin Code: 1
Guardian's Phone Number 1
kode skool
Student Name: 2 Roll No: 2
Class: 2 Section: 2
Address 2
2
City: 2 Pin Code: 2
Guardian's Phone Number 2
-------------------------------------------------------------------
kode skool
Student Name: 1 Roll No: 1
Class: 1 Section: 1
Address 1
1
City: 1 Pin Code: 1
Guardian's Phone Number 1
kode skool
Student Name: 1 Roll No: 1
Class: 1 Section: 1
Address 1
1
City: 1 Pin Code: 1
Guardian's Phone Number 1
【问题讨论】:
-
when I try to call a list value it's always the first index value that comes不清楚。老实说,我根本无法对它做出正面或反面。请显示示例输出与您期望的输出。另外,您的示例不是minimal reproducible example,因为您还没有定义i、new_line、no_of_classes或class_strength,并且您说ignore unnecessarily complex formatting part这表明您可以删除它并且仍然有这是问题的一个例子。 -
抱歉让问题变得如此含糊。第一个索引值是指列表的第一个值。
-
好的,很酷,当你处理完我提到的其他事情时告诉我,以便我尝试帮助你。
-
它是 for 循环的一部分,我用它来让 student_info() 运行几次。 [ for i in range (1,class_strength) ] 是准确的行
-
请提供minimal reproducible example;不需要完整的输出来证明列表是否正在更新。函数
student_info看起来不错,但您没有显示 调用 函数的方式或位置,也没有显示range中使用的值如何(或是否)与您想要的两个列表相关更新。
标签: python list function append