首页 > 解决方案 > 没有 db 的 Python 收银员

问题描述

所以我的任务是只使用 python 构建一个 python 收银员程序。不使用分贝。我使用 dict 和 keys 方法来构建它。所以我有两个问题:

  1. 我可以知道如何在资金余额部分之后保持程序运行,同时我仍在保存当前的资金余额状态吗?就像,使它成为一个连续的程序,而不仅仅是一次。
  2. 我想全面回顾一下这个任务的想法,它是如何写的,等等。你会用其他方式吗?如果是这样,我想听听如何。请记住,我的任务是构建没有任何外部库\db 的 python 收银员。

代码:

print('welcome to python cashier')
money = int(input('enter cashier current money\n'))


prices = {"small popcorn" : 3, "medium popcorn" : 5,
             "large popcorn" : 8, "small drink" : 1,
              "medium drink" : 2, "large drink" : 3 }
 

def calc(money, prices):
      try:
         itemchange = pay - itemvalue  
      except Exception as e:
        print(e)
      finally:
        print(f'change: {itemchange}') 

def show(money, prices): 
     try:
         for key,value in prices.items():
            print (f'{key}: {value}')
     except Exception as e:
         print(e)
     finally:
         return False
show(money, prices)

def start(money, prices):
     try:
     
        for key, value in prices.items():
          global item
          item = str(input('enter what you want to buy:\n'))
          if (item in prices.keys()):
            global itemvalue
            itemvalue = prices.get(item)
            print(f'{item}: {itemvalue}')
            global pay
            pay = float(input('how much costumer pay?\n'))
            return calc(money, prices)
          else:
            print('item not found')
     except Exception as e:
           print(e)
     finally:
           moneybalance = money + itemvalue
           print(f'moneybalance: {moneybalance}')
              

start(money, prices)

标签: python

解决方案


  1. 真正的问题是是否有人要求您保存信息。正如您所说,他们在任务中要求在没有数据库的情况下执行此操作,我认为您不需要这样做。顺便说一句,如果它没有实际的数据库,您可以只使用 .txt 文件来保存信息。检查 Python 中的“打开”功能。

快速示例:

with open('save.txt', 'w') as file:
    file.write(str(cash)) # cash is an integer.

这是一个写文件的例子。顺便说一句,我认为他们不希望您保存信息。在你应用一些东西之前检查它,以免破坏你的工作:)。

  1. 我建议将所有变量声明放在脚本的开头并添加一个“main”函数。从name == ' main '调用 main 函数。我也建议你做一个更详细的函数名称。尽量不要在这个小代码中使用全局变量(你可以在开始时声明它,它会是全局的,并且更容易阅读你的代码并更快地理解它)。我认为在您的第一个问题中,您是否考虑过让您的程序在任何程序运行中运行不止一次?如果我是正确的,请阅读 Python 循环 :)。你也用 str() 包装了你的输入返回,它没用,因为输入的返回值已经是 str (字符串类型)。

快速示例:

# Variables Declaration (Just an example for the structure).
ABC = 0
cash = 1000

# Functions Declaration
def calculate_price(money, prices):
    # Code Here.
    pass

def main():
    # The code of your start function, you don't need and arguments for this.
    pass

if __name__ == '__main__':
    main() # Call main here.

通过这种方式,您的代码将易于阅读并且易于分析:)。


推荐阅读