Python暗拍程序问题:竞拍者name与bid无法完整存入data_base
Python暗拍程序数据丢失问题修复
问题描述
开发的Python暗拍程序流程为:询问竞拍者姓名(name)、出价(bid),之后询问是否还有其他竞拍者;若输入yes则清除终端屏幕,避免后续竞拍者看到之前的出价。但运行时发现,data_base仅能记录后两位竞拍者(Mikey、Josh)的信息,首位竞拍者Gael的name和bid丢失。
程序运行输出
What is your name?: Gael What is your bid: $560 Are there any other bidders? Type 'yes or 'no'. yes [({'Gael': ['560']},)] What is your name?: Mikey What is your bid: $350 Are there any other bidders? Type 'yes or 'no'. yes [({'Mikey': ['350']},)] What is your name?: Josh What is your bid: $298 Are there any other bidders? Type 'yes or 'no'. no
最终输出(数据丢失)
[({'Mikey': ['350']},), ({'Josh': ['298']},)]
原代码
import os while True: name = input("What is your name?: ") bid = input("What is your bid: $") other_user = input("Are there any other bidders? Type 'yes or 'no'.\n") if other_user == 'yes': os.system('cls') data_base = [ ] def new_user(name, bid): brandnew_user = { name: [bid] }, data_base.append(brandnew_user) new_user(name, bid) print(data_base) if other_user == 'no': break
问题原因
data_base被重复初始化:每次输入yes时,代码会执行data_base = [],将列表重置为空,导致之前存储的竞拍者数据被清空。- 函数定义放在循环内部:
new_user函数在while循环内部定义,每次循环都会重新创建该函数,属于冗余操作,且可能引发作用域问题。 - 逻辑顺序错误:先判断是否有其他竞拍者并重置列表,再添加当前用户数据,导致首次输入
yes后,后续循环会丢失之前的数据。
修复方案
- 将
data_base初始化移到while循环外部,确保全程使用同一个列表存储数据。 - 将
new_user函数定义移到循环外部,避免重复定义。 - 调整逻辑顺序:先将当前用户数据添加到
data_base,再处理"是否有其他竞拍者"的判断及清屏操作。
修复后的代码
import os # 初始化全局数据存储列表 data_base = [] def new_user(name, bid): # 去掉多余逗号,避免生成不必要的元组 brandnew_user = {name: [bid]} data_base.append(brandnew_user) while True: name = input("What is your name?: ") bid = input("What is your bid: $") # 先添加当前用户数据到数据库 new_user(name, bid) other_user = input("Are there any other bidders? Type 'yes' or 'no'.\n") if other_user == 'yes': os.system('cls') elif other_user == 'no': break print("最终竞拍数据:") print(data_base)
修复后运行效果
首位竞拍者Gael的数据会被保留,最终输出将包含所有竞拍者信息:
[{'Gael': ['560']}, {'Mikey': ['350']}, {'Josh': ['298']}]
内容的提问来源于stack exchange,提问作者DJ MASK
相关产品推荐
相关产品推荐

