Home Backend Development Python Tutorial Python3 implements shopping cart function

Python3 implements shopping cart function

May 10, 2018 pm 02:18 PM
python3 Function shopping cart

这篇文章主要为大家详细介绍了Python3实现购物车功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Python3实现购物车功能的具体代码,供大家参考,具体内容如下

购物车要求:

1、启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表

2、允许用户根据商品编号购买商品

3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒

4、可随时退出,退出时,打印已购买商品和余额

5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示

6、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买

7、允许查询之前的消费记录

逻辑图:

执行代码:

#!/usr/bin/env python3
# Author: Robert
# --*-- coding: utf-8 --*--

set = False  #设置set 当输入为q就可以退出
file = open("购物车用户信息档案.txt","r+",encoding="utf-8")  #读取购物车用户信息文件
f = str(file.read())  #将文件内容转化成字符串
for line in f:
  file_str = str(f)
data = eval(file_str)  #将字符串转换为字典data

name = input("输入姓名:")
password = input("输入密码:")
while True:
  if name in data:      #用户在档案中
    if password in data[name]:     #密码和用户名对应,校验正确,登录。
      salary = float(data[name][password])
      print('''\033[32;1m欢迎登录,当前余额为%s\033[0m'''%salary)
      break
    else:      #否则密码错误,请重新输入
      password = input("密码错误,请重新输入:")
      continue
  else:      #否则判断为首次登录,将用户名,密码,工资存到用户信息文件中
    password_salary = {}
    salary_str = input("欢迎首次登录,请输入你的工资:")
    salary = float(salary_str)
    password_salary[password] = salary     #工资对应到密码
    data[name] = password_salary      #将密码-工资对应到用户名
    file.seek(0)
    file.write(str(data))
    file.tell()
    break

list = [#购物清单
  ["iphone",5800],
  ["sifei",800],
  ["macbook",17500],
  ["book",75],
  ["apple",5]
]

file_list_r = open("历史购物信息.txt","r+",encoding="utf-8")
file_list_r = str(file_list_r.read())
shoppinglist_dict = eval(file_list_r)
if name not in shoppinglist_dict:
  shoppinglist_dict[name] = []
shoppinglist = shoppinglist_dict[name]
shoppinglist_dict_now = []
choose = input("\n是否需要查询历史购物记录(y/n):")
if choose == 'y':
  print("\n\n---------->历史购物记录<----------")
  print(shoppinglist)
  print("---------->结束<----------")

while not set:   #购物车开始
  print("---------->商品清单<----------")
  for index,item in enumerate(list,1):
    print(index,item)
  print("---------->结束<----------")
  number = input("请输入想购买商品编号:")
  if number == "q":
    set = True
    data[name][password] = str(salary)
    file.seek(0)
    file.write(str(data))
    file.tell()
    print("---------->购物清单<----------")
    print(shoppinglist)
    print("您的余额:",salary)
    print("---------->结束<----------")
    shoppinglist.extend(shoppinglist)
    shoppinglist_dict[name] = shoppinglist
  elif number.isdigit() == False:
    print("\033[31;1m输入不是编号内容,请重新输入\033[0m")
  elif int(number)>int(len(list)) or int(number)<= 0:     #输入值不在清单中,报错
    print("\033[31;1m您所购买的商品不在清单中\033[0m")
  else:
    number_buy = int(number)-1
    if list[number_buy][1]<(salary):      #如果余额足够,提示购买成功并显示余额。
      salary = salary - int(list[number_buy][1])
      msg = &#39;\033[32;1m您已经将%s加入购物车中,余额为%d\033[0m&#39;%(list[number_buy][0],salary)
      print(msg)
      shoppinglist.append(list[number_buy])      #将本次购物信息加到购买记录中
    else:
      print("\033[31;1m余额不足,无法购买!\033[0m")      #提示余额不足
Copy after login

购物车用户信息档案.txt

{'name': {'password': '10000'}, 'cx': {'123': '725.0'}, 'robert': {'qw': '440.0'}, 'cv1': {'1': 100.5}, 'ROBERT': {'QW': 1560.0}, 'qwe': {'qw': '1555.0'}}

历史购物信息.txt

{'name': [['iphone', 5800],['bike', 800]], 'cx':[['iphone', 5800],['apple', 5],['apple', 5], ['book', 75]]}

相关推荐:

python购物车程序代码

Python实现购物车程序




The above is the detailed content of Python3 implements shopping cart function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What functions does Doubao app have? What functions does Doubao app have? Mar 01, 2024 pm 10:04 PM

There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

Comparative analysis of the functions and performance of JPA and MyBatis Comparative analysis of the functions and performance of JPA and MyBatis Feb 19, 2024 pm 05:43 PM

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

What is a Bluetooth adapter used for? What is a Bluetooth adapter used for? Feb 19, 2024 pm 05:22 PM

What does a Bluetooth adapter do? With the continuous development of science and technology, wireless communication technology has also been rapidly developed and popularized. Among them, Bluetooth technology, as a short-distance wireless communication technology, is widely used in data transmission and connection between various devices. The Bluetooth adapter plays a vital role as an important device that supports Bluetooth communication. A Bluetooth adapter is a device that can turn a non-Bluetooth device into a device that supports Bluetooth communication. It realizes wireless connection and data transmission between devices by converting wireless signals into Bluetooth signals. Bluetooth adapter

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly Implement Return to Previous Page Function PHP Tips: Quickly Implement Return to Previous Page Function Mar 09, 2024 am 08:21 AM

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

What is Discuz? Definition and function introduction of Discuz What is Discuz? Definition and function introduction of Discuz Mar 03, 2024 am 10:33 AM

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

See all articles