首页 > 解决方案 > python循环中的变量

问题描述

如何在每次运行后(例如可以是 3 人)保存每个变量(salary 和 cost_car)的数据,以便以后使用它进行计算。

nr = int(input("How many people: "))
total = 0

for i in range(1, nr+1, 1):
    print("For person ",i)
    salary = float(input("Salary per month : "))
    cost_car = float(input("Cost per month for car: "))  

标签: pythonloops

解决方案


您可以使用多种数据结构将数据存储在正在运行的程序中。由于您的人员在您的示例中被编号,因此将每个人的信息存储在列表中是有意义的。您可以将每个人的信息表示为一个简单的字典,其中的键代表不同信息的名称:

nr = int(input("How many people: "))
total = 0

persons_info = []

for i in range(1, nr+1, 1):
    print("For person ",i)
    salary = float(input("Salary per month : "))
    cost_car = float(input("Cost per month for car: "))
    
    info = {salary: salary, cost_car: cost_car} # the info of person i
    persons_info.append(info) # store it in the list of all persons info

然后,您可以在 for 循环之后通过执行以下操作检索人员 n 的信息:(persons_info[n-1]因为列表索引从 0 开始),这将为您提供他们信息的字典。

更好的方法是用一个对象来表示每个人,即表示与真实人相关的信息Person的某个类的实例。Person这样,您还可以包含并实现您希望在Person类中执行的不同操作:

class Person:
    def __init__(self, salary, cost_car):
        self.salary = salary
        self.cost_car = cost_car
    
    def getNetWorth(self):
        return self.salary + self.cost_car

nr = int(input("How many people: "))
total = 0

persons = []

for i in range(1, nr+1, 1):
    print("For person ",i)
    salary = float(input("Salary per month : "))
    cost_car = float(input("Cost per month for car: "))
    
    person = Person(salary, cost_car) # an object representing person i
    persons.append(info) # store it in the list of all person objects

再次,您可以通过执行以下操作检索人员 n 的信息:(persons_info[n-1]因为列表索引从 0 开始),这将为您提供一个表示其信息的对象。


推荐阅读