首页 > 解决方案 > 程序没有正确考虑价格

问题描述

嗨,我对 Python 很陌生,所以我猜我在这里犯了一个非常明显的错误,但基本上我想让我的代码在这里做的是从用户那里获取 5 种产品及其价格,但是这些产品正在工作当用户输入高于 0 的价格时,会显示“请输入高于 0 的价格”的消息,这是我下面的代码,非常感谢对新手的任何帮助,谢谢。

#Lists of products and prices

products = []
price = [] #declare lists
total = 0 #declare variable to hold total of prices

#function which is used to read in values to each list in turn 
#range has been set to read in 5 values
def inputPrice():
    for counter in range(0,5):
        valid = False
        print (counter+1, "Enter 5 Products:")
        tempItems = input() #declare temp variable to hold input value
        products.append(tempItems) #add this value into our list
            #when reading in price if statement is added for validation
        print (counter+1, "Enter their prices:")
        tempCost = int(input())
        if tempCost<=0: #validate input
               print ("Incorrect price....")
               print ("Please enter a price above 0")
        else: 
            valid = True
            price.append(tempCost)

标签: pythonarraysinput

解决方案


更新您的代码添加 while 循环以从用户那里获取价格

产品清单和价格

products = []
price = [] #declare lists
total = 0 #declare variable to hold total of prices

#function which is used to read in values to each list in turn 
#range has been set to read in 5 values
def inputPrice():
    for counter in range(0,5):
        valid = False
        print (counter+1, "Enter 5 Products:")
        tempItems = input() #declare temp variable to hold input value
        products.append(tempItems) #add this value into our list
            #when reading in price if statement is added for validation
        while True:
          print (counter+1, "Enter their prices:")
          tempCost = int(input())
          if tempCost<=0: #validate input
               print ("Incorrect price....")
               print ("Please enter a price above 0")
          else:
            break
        else: 
            valid = True
            price.append(tempCost)
            
inputPrice()

推荐阅读