首页 > 解决方案 > 可以计算不同产品价值、折扣等的 Python 代码,供商店客户使用

问题描述

我目前正在尝试创建一个代码,以帮助商店中需要:

我只研究了上面的前四点,但我对如何创建和打印收据一无所知。到目前为止,这是我的代码:

#This part greets the user, and lets the user know that the application has started
print("Hello there!")
#This starts off the loop, but this variable may be changed later on
cont = "yes"
#This is the actual loop
while cont == "yes" or cont == "Yes" or cont == "YES":
  print("Choose an option below:")
#This shows the options
  print("1) Calculate the value of different product sizes")
  print("2) Calculate the sale price")
  print("3) Calculate the discount")
  print("4) Create a shopping list")
  print("5) Exit")
#This part lets the user choose what they would like to do
  option = float(input("Choose an option (1/2/3/4/5): "))  
#This is what happens if the user chooses Option 4
  if option == 4:
#This is the "Shopping list" part of the application below
    import os,sys,time
    sl = []
    try:
      f = open("Your_shopping_list.txt","r")
      for line in f:
        sl.append(line.strip())
      f.close()
    except:
        pass
    def mainScreen():
      print("Your list contains",len(sl),"items.")
      print("Please choose from the following options:")
      print("1) Add to the list")
      print("2) Delete from the list")
      print("3) View the list")
      print("4) Quit the program")
      choice = input("Enter your choice here (1/2/3/4): ")
      if len(choice) > 0:
        if choice == "1":
          addScreen()
        elif choice == "2":
          deleteScreen()
        elif choice == "3":
          viewScreen()
        elif choice == "4":
          sys.exit()
        else:
          mainScreen()
      else:
        mainScreen()
    def addScreen():
      print("Please enter the name of the item that you want to add.")
      print("Press ENTER to return to the main menu.")
      item = input("Item: ")
      if len(item) > 0:
        sl.append(item)
        print("Item added.")
        saveList()
        time.sleep(1)
        addScreen()
      else:
        mainScreen()
    def viewScreen():
      for item in sl:
        print(item)
      print("Press ENTER to return to the main menu")
      input()
      mainScreen()
    def deleteScreen():
      global sl
      count = 0
      for item in sl:
        print(count, " - ", item)
        count = count + 1
      print("Press ENTER to return to the main menu.")
      print("Which item do you want to remove?")
      choice = input("Enter your choice here: ")
      if len(choice) > 0:
        try:
          del sl[int(choice)]
          print("Item deleted...")
          saveList()
          time.sleep(1)
        except:
          print("Invalid number")
          time.sleep(1)
        deleteScreen()
      else:
        mainScreen()
    def saveList():
      f = open("Your_shopping_list.txt", "w")
      for item in sl:
        f.write(item)
        f.close()
      mainScreen()
#This is what happens if the user chooses Option 1
#This is the part that calculates the value of up to 10 products
  if option == 1:
#This notifies the user that there can only be up to 10 product sizes entered
    print("Please note: This code can only take up to 10 product sizes.")
#This asks the user how many products there are
    products = int(input("How many products are there? "))
#This is just in case the user still types that there are over 10 products
    if products > 10:
      print("This code can only take up to 10 product sizes.")
      print("Please enter only up to 10 product sizes below.")
    if products <= 1:
#This tells the user that they must enter at least 2 product sizes to compare them
      print("You must enter at least two product sizes to compare.")
    if products >= 1:
#This asks for information because the user may just be looking for the $/g.
      cost1 = float(input("Cost of first product($): "))
      mass1 = float(input("Mass of first product(g): "))
      ans1 = cost1/mass1
      a = ans1
#This part substitutes undefined variables with a blank
#This is in case the number of sizes being compared doesn't reach 2 to 10
      ans2 = ""
      ans3 = ""
      ans4 = ""
      ans5 = ""
      ans6 = ""
      ans7 = ""
      ans8 = ""
      ans9 = ""
      ans10 = ""
#This is for when there are two or more product sizes
    if products >= 2:
      cost2 = float(input("Cost of second product($): "))
      mass2 = float(input("Mass of second product(g): "))
      ans2 = cost2/mass2
      if a > ans2:
        a = ans2
#This is for when there are three or more product sizes
    if products >= 3:
      cost3 = float(input("Cost of third product($): "))
      mass3 = float(input("Mass of third product(g): "))
      ans3 = cost3/mass3
      if a > ans3:
        a = ans3
      ans4 = ""
      ans5 = ""
      ans6 = ""
      ans7 = ""
      ans8 = ""
      ans9 = ""
      ans10 = ""
#This is for when there are four or more product sizes
    if products >= 4:
      cost4 = float(input("Cost of fourth product($): "))
      mass4 = float(input("Mass of fourth product(g): "))
      ans4 = cost4/mass4
      if a > ans4:
        a = ans4
      ans5 = ""
      ans6 = ""
      ans7 = ""
      ans8 = ""
      ans9 = ""
      ans10 = ""
#This is for when there are five or more product sizes
    if products >= 5:
      cost5 = float(input("Cost of fifth product($): "))
      mass5 = float(input("Mass of fifth product(g): "))
      ans5 = cost5/mass5
      if a > ans5:
        a = ans5
      ans6 = ""
      ans7 = ""
      ans8 = ""
      ans9 = ""
      ans10 = ""
#This is for when there are six or more product sizes
    if products >= 6:
      cost6 = float(input("Cost of sixth product($): "))
      mass6 = float(input("Mass of sixth product(g): "))
      ans6 = cost6/mass6
      if a > ans6:
        a = ans6
      ans7 = ""
      ans8 = ""
      ans9 = ""
      ans10 = ""
#This is for when there are seven or more product sizes
    if products >= 7:
      cost7 = float(input("Cost of seventh product($): "))
      mass7 = float(input("Mass of seventh product(g): "))
      ans7 = cost7/mass7
      if a > ans7:
        a = ans7
      ans8 = ""
      ans9 = ""
      ans10 = ""
#This is for when there are eight or more product sizes
    if products >= 8:
      cost8 = float(input("Cost of eighth product($): "))
      mass8 = float(input("Mass of eighth product(g): "))
      ans8 = cost8/mass8
      if a > ans8:
        a = ans8
      ans9 = ""
      ans10 = ""
#This is for when there are nine or more product sizes
    if products >= 9:
      cost9 = float(input("Cost of ninth product($): "))
      mass9 = float(input("Mass of ninth product(g): "))
      ans9 = cost9/mass9
      if a > ans9:
        a = ans9
      ans10 = ""
#This is for when there are ten or more product sizes
    if products >= 10:
      cost10 = float(input("Cost of tenth product($): "))
      mass10 = float(input("Mass of tenth product(g): "))
      ans10 = cost10/mass10
      if a > ans10:
        a = ans10
#There's nothing for 10+ sizes for there is no loop for it'll make the code too long
#This tells the user the which product size(s) is/are the ones with the best value
#This tells the user the final result
    if products >= 1:
      print("The product(s) with the best value is/are the below product number(s):")
      if ans1 == a:
        print(1)
      if ans2 == a:
        print(2)
      if ans3 == a:
        print(3)
      if ans4 == a:
        print(4)
      if ans5 == a:
        print(5)
      if ans6 == a:
        print(6)
      if ans7 == a:
        print(7)
      if ans8 == a:
        print(8)
      if ans9 == a:
        print(9)
      if ans10 == a:
        print(10)
#This tells the user the cost per gram of the product(s) with the best value is/are
      print("The cost per gram is $", a, "/ g")
#This tells the user to pick the size with best quality if multiple are above
#Sometimes, items with the best value may not have the best quality.
      print("If there are multiple options above, choose the one with best quality.")
#This is what happens if the user chooses Option 2
#This calculates the price after a discount
  if option == 2:
#This asks for the ticket (original) price of a specific product
    p = float(input('The ticket (original) price($): '))
#This asks for the discount (in percentage) of a specific product
    d = float(input('The discount(%): '))
#This then puts the information together and calculates the discount...
    s = (d*0.01)
    ps = (p*s)
    answer = (p - ps)
    answer2 = str(round(answer, 2))
    print('The discount is $', ps)
#... and also the final discounted price.
#Finally, it tells the user the result
    print('The final price is $', answer2)
#This is what happens if the user chooses Option 3
#This calculates the discount (in percentage)
  if option == 3:
#This collects information about what the ticket (original) price was
    o = float(input('The ticket (original) price($): '))
#This asks what the price of the product after the discount is
#Then it takes all the information, puts them together and calculates the discount(%)
    d = float(input('Price after the discount($): '))
    p = 100/(o/d)
    p = str(round(p, 2))
#Finally, it tells the user the result
    print('The percentage discount is', p,'%')
#This is the final option, which is for the user to quit using this application
  if option == 5:
#This asks the user one last time in case they accidentally pressed 5.
    exit = input("Are you sure you want to exit? (Yes/No): ")
#There are three versions of "Yes" to make the application more user-friendly
    if exit == "yes":
#"Thank you and goodbye" thanks the user for using this application
#Then, it says goodbye and ends the application
      print("Thank you and goodbye!")
      cont = 'no'
    if exit == "Yes":
      print("Thank you and goodbye!")
      cont = 'no'
    if exit == "YES":
      print("Thank you and goodbye!")
      cont = 'no'
#But if exit doesn't equal "Yes" or "yes" or "YES", then cont still equals "yes".
#And if cont = "yes", then the loop restarts.
#This is if the user doesn't choose any of the above and enters an invalid input
  elif option != 1:
    if option != 2:
      if option != 3:
        if option != 4:
          if option != 5:
            print('Invalid input')
#This asks if the user would like to continue or quit
            cont = input('Continue? (Yes/No): ')
#To make the application more user-friendly, there are again three versions of "No"
            if cont == 'No':
#"Thank you and goodbye" thanks the user for using this application
#Then, it says goodbye and ends the application
              print("Thank you and goodbye!")
            if cont == 'no':
              print("Thank you and goodbye!")
            if cont == 'NO':
              print("Thank you and goodbye!")

标签: pythonpython-3.x

解决方案


以下是一些改进:

1.使用类代替存储不同的相关事物

class Ingredient():
    def __init__(self, name):
        self.name = name
        self.cost = float(input(f"Cost of {self.name}($): "))
        self.mass = float(input(f"Mass of {self.name}(g): "))
        self.ans = cost6 / mass6

2.那么你不需要十个答案变量。您可以使用列表

错误的:

ans2 = ""
ans3 = ""
...
option1 = input()
option2 = input()
...      

正确的:

ingredients = []
for i in range(0, products):
    ing = Ingredient("Product " + str(i + 1))
    ingredients.append(ing)

3.使用列表比较不同的选项

elif option != 1:
    if option != 2:
      if option != 3:
        if option != 4:
          if option != 5:

可以替换为

if option not in [1, 2, 3, 4, 5]:

 if exit == "yes":
      print("Thank you and goodbye!")
      ...

可能

if exit in ["yes", "YES", "Yes"]:
    print("Thank you and goodbye!")
    cont = 'no'

同样的cont == No


然后显示收据将很容易

totalCost = 0
for item in ingredients:
    print(item.name, str(item.cost), str(item.mass))
    totalCost += item.cost
print(totalCost + "$")

推荐阅读