我如何编写一个 while 循环来启动、停止并从它停止的地方重新开始?

问题描述 投票:0回答:1

下面的例子是我正在处理的一个 while 循环。 我想做的是制作一个循环来计算员工人数(例如:员工 1、员工 2)。我还希望能够设置它,如果员工数量停止并重新启动,程序将能够记住最后使用的员工编号并从那里继续

name = 'a'
state = 'las vegas'
occupation = 'vet'

x = 1
while x > 0: 
    employee = x 
    name = changes_after_every_loop
    state = changes_after_every_loop
    occupation = changes_after_every_loop
x = x + 1
python if-statement while-loop counter
1个回答
0
投票

如果您需要在会话之间保持状态,那么您需要以某种方式备份数据,例如将数据写入磁盘。例如,这个类将遍历员工列表,做一些事情,当用完列表时,会将最后一个 ID 保存到磁盘。重新启动时,它将继续从保存的 id 开始:

from pathlib import Path

class EmployeeCount:
    def __init__(self, employee_names: list[str], employee_states: list[str], occupations: list[str]):
        self.names = employee_names
        self.states = employee_states
        self.occupations = occupations
        
        self.starting_employee_id = self._check_cached_id()
        
    def create_employees(self):
        for idx, (name, state, occupation) in enumerate(zip(self.names, self.states, self.occupations)):
            employee_id = idx + self.starting_employee_id
            print(f'Current employee id: {employee_id}')
            # do something
        # when runs out of data save the last id to disk for example
        self._backup_id(employee_id)
        
    def _backup_id(self, employee_id: int):
        with open('id_backup.txt', 'w') as f:
            f.write(f'{employee_id}')
    
    def _check_cached_id(self) -> int:
        if not Path('id_backup.txt').is_file():
            return 0
        with open('id_backup.txt', 'r') as f:
            return int(f.readline()) + 1

然后我们可以使用它:

n = ['anna', 'frank', 'terry']
s = ['a', 'b', 'c']
o = ['d', 'e', 'f']

ec = EmployeeCount(n, s, o)
ec.create_employees()

哪些输出:

Current employee id: 0
Current employee id: 1
Current employee id: 2

当我们再次运行它时,它从保存的 id 继续:

n2 = ['bill', 'ted']
s2 = ['d', 'e']
o2 = ['r', 'k']

ec = EmployeeCount(n2, s2, o2)
ec.create_employees()
Current employee id: 3
Current employee id: 4

但在这种情况下,更好的选择是某种数据库。

© www.soinside.com 2019 - 2024. All rights reserved.