Skip to main content
 首页 » 编程设计

python之为什么代码返回错误的乘法

2025年05月04日11lovecherry

我的学习问题是: 定义一个过程,total_enrollment, 将元素列表作为输入, 其中每个元素都是一个包含的列表 三要素:大学名称, 注册学生总数, 以及每年的学费。

程序应该返回两个数字, 不是字符串, 给出学生总数 就读于所有的大学 在列表中,以及总学费 (这是数字的总和 学生入学时间 每所大学的学费)。

给出的代码是:

usa_univs = [ ['California Institute of Technology',2175,37704], 
          ['Harvard',19627,39849], 
          ['Massachusetts Institute of Technology',10566,40732], 
          ['Princeton',7802,37000], 
          ['Rice',5879,35551], 
          ['Stanford',19535,40569], 
          ['Yale',11701,40500]  ] 

我的解决方案是:

def total_enrollment(a): 
    total_students = 0 
    costsum = 0 
    for e in a: 
        total_students = total_students + e[1] 
        costsum = costsum + e[2] 
    all_in_all = total_students * costsum 
    return total_students 
    return all_in_all 

我应该看到的是: 77285,3058581079

实际出来的是: 77285 - 没有总数

请您参考如下方法:

你不能从一个函数中返回两次。您可以将这两个值作为 tuple 返回:

return total_students, all_in_all 

然后将返回值解压到两个变量中。

例如:

>>> def func(): 
...     return 1, 2 
...  
>>> v1, v2 = func() 
>>> v1 
1 
>>> v2 
2