Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

python 3.x - I am having trouble with if statements and possibly a def function

So when running the code, it works as intended except for the fact that when looped a second time, the if statement doesn't work. May I ask for some help please.

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()
question from:https://stackoverflow.com/questions/65952590/i-am-having-trouble-with-if-statements-and-possibly-a-def-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are a couple of ways to implement what you want to do.

  • Using Functions, which is the approach you seem to be trying to implement
  • Using classes, which would be a more Object oriented approach

The Functional Approach

In the functional approach all operations are managed by individual functions, and many of the essential variables are passed to these functions. Here are the implemented functions:

# 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:
"
    for i in range(len(kylist)):
            s += f'{i+1:4}{kylist[i]:10} {inv[kylist[i]]} each
'
    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:
"
    s += 'ItemQtyCost
'
    for ky in ckys:
        qty = cart[ky]
        cost= qty* inv[ky]
        s += f'{ky}{qty}{cost}
'
    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 function which then controls process flow and manages calling necessary functions includes:

# 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 

A typical execution of this main routine would look like:

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!

A more Object Oriented Approach

In the OO approach, many of the basic operations are implemented as methods within a Cart Class. Using the Cart Class groups methods together and keeps them associated with the cart. The following gives an implementation using the Cart Class.

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:
"
        for i in range(len(kylist)):
                s += f'{i+1:4}{kylist[i]:10} {self._inv[kylist[i]]} each
'
        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:
"
        s += 'ItemQtyCost
'
        for ky in ckys:
            qty = self._cart[ky]
            cost= qty* self._inv[ky]
            s += f'{ky}{qty}{cost}
'
        return s
 
    @property
    def bill(self):
        total = 0
        for itm, qty in self._cart.items():
            total += qty*self.price(itm)
        return total

Using the Cart Class for most of the needed methods, leaves only 1 separate function

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 function which manages the entire application would then look like:

# 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        

Executing this Main method would produce results like:

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!
?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...