当前位置: 动力学知识库 > 问答 > 编程问答 >

In Python, how do I create a new variable each time a loop goes around, and then send them all to a function to be processed?

问题描述:

I'm still relatively new to python, and this is probably way out of my ability, but I'm working on a program (For a school programming course) that asks for a new item, the price of that item, and the quantity of that item each time a loop goes around. (The loop will be stopped by typing stop when the program asks if there are more items to process) The program will then sends all those variables to a module I created that will calculate the total cost of each item based on the quantity, and then print out the cost of each item, and the total cost.

My teacher says this is possible, but he doesn't quite know how to do it.

Here's what I have so far (I tried to use a list, but it doesn't seem to be working out):

First Program (total_run.py):

import total_cost

itemname = []

itemprice = []

quantity = []

stop = "go"

while stop != "stop":

itemname.append(input("What is the name of the item?\n"))

itemprice.append(float(input("What is the price of the item?\n")))

quantity.append(float(input("How many of these items are there?\n")))

stop = input("Enter \"stop\" to add up the total")

name,price = total_cost.total(itemname,itemprice,quantity)

totalprice = total_cost.final(itemprice)

#Not sure how to print an unknown number of times

print(name," $",price)

print("Your total is: $", totalprice)

Second Program (total_cost.py):

#Calculates all the costs

itemprice = 0

def total(itemname,itemprice,quant):

itemprice = 0

itemname = itemname

for values in quant:

itemprice *= values

return itemname,itemprice

def final(itemprice):

finalcost = itemprice += itemprice

#I'm not sure on how to add up all the items in a list

return finalcost

网友答案:

Your data structures are wrong. Really you just want a single list of items, and each item in that list is itself a list (or a tuple) of name, price, quantity. Then you can simply add up the prices of each item in the list.

items = []
while stop != "stop":
    name = input("What is the name of the item?\n")
    price = float(input("What is the price of the item?\n"))
    quantity = float(input("How many of these items are there?\n"))
    items.append((name, price, quantity))

Now you can easily calculate the total per item, and the overall total:

overall_total = 0
for item in items:
    total_price = item[1] * item[2]
    overall_total += total_price
网友答案:

You can keep the lists in separately, and then iterate through them with a for loop like so:

costs = []
while stop != "stop":
    itemname.append(input("What is the name of the item?\n"))
    itemprice.append(float(input("What is the price of the item?\n")))
    quantity.append(float(input("How many of these items are there?\n")))
    stop = input("Enter \"stop\" to add up the total")

for i in range(len(itemname)):
    costs.append(itemprice[i]*quantity[i]) 

total_cost = sum(costs)

Noteworthy things (can't comment, so part of answer here, sorry):

  1. In total_cost.total, you define itemprice = 0 and then multiply by it itemprice *= values so itemprice will remain 0
  2. You pass itemprice and itemname to the total_cost.total function, and then redefine itemprice = 0 and reassign itemname to itself (doesn't break the code though)
  3. Strings in python can be defined by " or ', and the other will not stop the string. so my_string = "Hello, it's a nice day out" or stop = input('Enter "stop" to total the price up') will work.
  4. You can print an unknown amount of items by iterating through the list with a for loop (as shown above

Cheers

网友答案:

As Daniel said, it's better to pack data about one item into one creature.
He suggests tuple, I suggest class:

class Item:
    def __init__(self, name=None, price=None, quantity=None):
        self.name, self.price, self.quantity = name, price, quantity
    @classmethod
    def ask_user(cls):
        return cls(input('The name of Item: '), float(input('The price: ')), float(input('How much of Items you have: ')))
    def value(self):
        return self.price * self.quantinity

def total_value(items):
    sum = 0
    for i in items:
        sum += i.value()
    return sum

Also, instead of waiting for "stop", you can wait for End-Of-File
(Linux: Ctrl+D in empty line, Windows: Ctrl+Z, then Enter):

items = []

while True:
    try:
        items.append(Item.ask_user())
    except EOFError: #no mire items to read
        break #exit from the loop
    except Exception as e: #other error
        print(type(e), e)  #print its type and the message

print(total_value(items))
分享给朋友:
您可能感兴趣的文章:
随机阅读: