python - 程序没有正确考虑价格
问题描述
嗨,我对 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)
解决方案
更新您的代码添加 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()
推荐阅读
- angular - Angular mat-datepicker 页面更改事件
- sharepoint-online - kw 搜索上的 SharePoint 不熟悉错误:SubstrateSearchException: Remote executors failed
- python - 通过python中的beautifulsoup从yahoofinance中提取表数据
- ubuntu-16.04 - 安装 libgnutls-deb0-28 ubuntu 16.04
- clickhouse - 将 clickhouse 存储路径设置为网络共享文件夹
- reactjs - 有没有办法从 URL 加载高分辨率图像 - 首先是低分辨率,然后是加载低分辨率后的高分辨率?
- ios - 连接 30 台 iPad
- python - 在 Python 字典中添加缺失值
- android - 如何在多个类中使用一个特定函数,而无需在 Kotlin 的所有类中实际复制其代码?
- sql - 在 phpmyadmin 中创建一个 sql 查询