首页 > 解决方案 > 我在使用 if 语句和可能的 def 函数时遇到问题

问题描述

因此,在运行代码时,它按预期工作,除了第二次循环时,if 语句不起作用。我可以请求一些帮助吗?

cart=[]
price_total=[]
stuff={"potato": 50, "apple": 35, "orange": 40, "banana": 25, "popcorn": 120, "water": 20, "cola": 
40}
y=1       


def main():
  print("Thanks for using checkout")
  print("(1) make a transaction")
  customer_input=int(input("What would you like to do:"))



main()
if customer_input==1:
  print("potato=50") 
  print("apple=35")
  print("orange=40")
  print("banana=25")
  print("popcorn=120")
  print("water=20")
  print("cola=40")
  global order_input
  order_input=input("What would you like to order:")
  cart.append(order_input)
  lol()

标签: python-3.x

解决方案


有几种方法可以实现您想要做的事情。

  • 使用函数,这似乎是您尝试实施的方法
  • 使用类,这将是一种更面向对象的方法

函数式方法

在函数式方法中,所有操作都由单独的函数管理,并且许多基本变量都传递给这些函数。以下是实现的功能:

# The Functional Approach
def getInput(prompt, respType= None):
    """Simple Function To Gather input and verify it's type,
       Returns the User input converted to the requested type
       if it is consistent with the type specifier"""
    while True:
        resp = input(prompt)
        if respType == str or respType == None:
            break
        else:
            try:
                resp = respType(resp)
                break
            except ValueError:
                print('Invalid input, please try again')
    return resp

def list_stock(inv):
    """Returns a printable list of all items currently in inventory """
    kylist = sorted(list(inv.keys()))
    s = "The Items currently in stock include:\n"
    for i in range(len(kylist)):
            s += f'{i+1:4}\t{kylist[i]:10} {inv[kylist[i]]} each\n'
    return s  

def add_to_cart(item, qty, cart):
    """Adds Item to cart and returns updated cart"""
    cdi = cart.pop(item, 0)
    cdi += qty
    cart[item] = cdi
    return cart

def contents(cart, inv):
    """Returns printable list of cart contents"""
    ckys = cart.keys()
    s = "The Items currently in your cart include:\n"
    s += 'Item\tQty\tCost\n'
    for ky in ckys:
        qty = cart[ky]
        cost= qty* inv[ky]
        s += f'{ky}\t{qty}\t{cost}\n'
    return s

def total_bill(cart, inv):
    """Returns the Total Cost of items in Cart"""
    total = 0
    for itm, qty in cart.items():
        total += qty*inv[itm]
    return total

def load_cart(cart, inv):
    stock = sorted(list(inv.keys()))
    print(list_stock(inv))
    while True:
        itm = stock[getInput('Please enter an item number to add to your cart', int)-1]
        qty = getInput(f'please enter the number of {itm} you want added to your cart', int)
        add_to_cart(itm, qty, cart)
        if  getInput("Do you have more to add? (y/n)").lower() != 'y':    
                break 

然后控制流程并管理调用必要函数的主要功能包括:

# The Main Method for Functional Appraoch
stuff={"potato": 50, "apple": 35, "orange": 40, "banana": 25, "popcorn": 120, "water": 20, "cola": 
40}
cart = dict()
print("Thanks for using checkout")
while True:
    if getInput('Would you like to load a cart? (Y/N)').lower()[0]  == 'y':
        load_cart(cart, stuff)
        print(contents(cart, stuff))
        print (f'Your total bill = {total_bill(cart, stuff)}' )       
    else:
        print('Have a nice day!')
        break 

此主例程的典型执行如下所示:

Thanks for using checkout
Would you like to load a cart? (Y/N) y
The Items currently in stock include:
   1    apple      35 each
   2    banana     25 each
   3    cola       40 each
   4    orange     40 each
   5    popcorn    120 each
   6    potato     50 each
   7    water      20 each

Please enter an item number to add to your cart 3
please enter the number of cola you want added to your cart 2
Do you have more to add? (y/n) n
The Items currently in your cart include:
Item    Qty Cost
cola    2   80

Your total bill = 80
Would you like to load a cart? (Y/N) n
Have a nice day!

更面向对象的方法

在 OO 方法中,许多基本操作都作为 Cart 类中的方法实现。使用购物车类将方法组合在一起并使它们与购物车相关联。下面给出了使用 Cart 类的实现。

class Cart:
    def __init__(self, inventory):
        self._cart = dict()
        self._inv = inventory
        
    def in_inventory(self, item):
        return item in self._inv.keys()
    
    @property
    def stock(self):
        return sorted(list(self._inv.keys()))
    
    def price(self, itm):
        return self._inv[itm]

    @property
    def inventory(self):
        kylist = self.stock
        s = "The Items currently in stock include:\n"
        for i in range(len(kylist)):
                s += f'{i+1:4}\t{kylist[i]:10} {self._inv[kylist[i]]} each\n'
        return s
    
    def add_to_cart(self, item, qty= 1):
        cdi = self._cart.pop(item, 0)
        cdi += qty
        self._cart[item] = cdi
        
    @property
    def contents(self):
        ckys = self._cart.keys()
        s = "The Items currently in your cart include:\n"
        s += 'Item\tQty\tCost\n'
        for ky in ckys:
            qty = self._cart[ky]
            cost= qty* self._inv[ky]
            s += f'{ky}\t{qty}\t{cost}\n'
        return s
 
    @property
    def bill(self):
        total = 0
        for itm, qty in self._cart.items():
            total += qty*self.price(itm)
        return total

对大多数需要的方法使用 Cart 类,只剩下 1 个单独的函数

def load_cart(cart):
    stock = cart.stock
    print(cart.inventory)
    while True:
        itm = stock[getInput('Please enter an item number to add to your cart', int)-1]
        qty = getInput(f'please enter the number of {itm} you want added to your cart', int)
        cart.add_to_cart(itm, qty)
        if  getInput("Do you have more to add? (y/n)").lower() != 'y':    
                break      

管理整个应用程序的主要功能将如下所示:

# The main routine to execute the Object Oriented Appraoch
stuff={"potato": 50, "apple": 35, "orange": 40, "banana": 25, "popcorn": 120, "water": 20, "cola": 
40}
cart = Cart(stuff)
print("Thanks for using checkout")
while True:
    if getInput('Would you like to load a cart? (Y/N)').lower()[0]  == 'y':
        load_cart(cart)
        print(cart.contents)
        print (f'Your total bill = {cart.bill}' )       
    else:
        print('Have a nice day!')
        break        

执行此 Main 方法将产生如下结果:

Thanks for using checkout
Would you like to load a cart? (Y/N) y
The Items currently in stock include:
   1    apple      35 each
   2    banana     25 each
   3    cola       40 each
   4    orange     40 each
   5    popcorn    120 each
   6    potato     50 each
   7    water      20 each

Please enter an item number to add to your cart 4
please enter the number of orange you want added to your cart 3
Do you have more to add? (y/n) n
The Items currently in your cart include:
Item    Qty Cost
orange  3   120

Your total bill = 120
Would you like to load a cart? (Y/N) n
Have a nice day!
​

推荐阅读