如何循环python列表输入验证?


newcompany = input("Enter Company Name: ")
for stock in portfolioStock:
if newcompany.lower() == stock[0].lower():
newcompany = input("Company already exist in the PortfolionPlease enter another Company Name: ")
break
else:
newcompany = newcompany.capitalize()
continue

上面的代码在进入下一个代码块之前只检查一次输入验证,我如何使它连续验证输入?例如,对于输入,我输入apple,但我的列表中有apple,所以它再次提示,但当我再次输入apple时,它只是移动到下一行代码。

Enter Company Name: apple
Company already exist in the Portfolio
Please enter another Company Name: apple
Enter market capitalisation of company: Mega, Large or Mid: 

这就是它的样子

下一个是while

newcompany = input("Enter Company Name: ")
while True:
for stock in portfolioStock:
if newcompany.lower() == stock[0].lower():
newcompany = input("Company already exist in the PortfolionPlease enter another Company Name: ")
break
else:
newcompany = newcompany.capitalize()
continue

这就是我的代码看起来像while循环这些是结果

Enter Company Name: apple
Company already exist in the Portfolio
Please enter another Company Name: apple
Company already exist in the Portfolio
Please enter another Company Name: samsung

它在Samsung下面留了一个空格,不延续到下一行代码

我不太清楚你在找什么。假设portfolioStock是列表的list,这可能适合您。

newcompany = input("Enter Company Name: ")
for stock in portfolioStock:
#Convert all elements in list to lowercase
stock = [x.lower() for x in stock]
#This loop wil continue as long as the input is equal to any value in stock
while newcompany.lower() in stock:
newcompany = input("Company already exist in the PortfolionPlease enter another Company Name: ")
newcompany = newcompany.capitalize()

使用while循环检查该公司是否已经存在,如果存在,它将不断提示您输入新名称。当有新名称时,它将被添加到列表

portfolioStock = ["Apple"]
company = input("Enter Company Name: ")
while company.capitalize() in portfolioStock: # e.g. 'Apple' is already in there
company = input("Company already exist in the PortfolionPlease enter another Company Name: ")
portfolioStock.append(company.capitalize())

谢谢MITCHELL olislager !!

newcompany = input("Enter Company Name: ")
for stock in portfolioStock:
while newcompany.lower() == stock[0].lower():
newcompany = input("Company already exist in the PortfolionPlease enter another Company Name: ")
newcompany = newcompany.capitalize()

因为我的portfolioStock是一个2D列表与str和int,我不得不编辑米切尔的代码一点点,但它的工作!!非常感谢!!

相关内容

  • 没有找到相关文章

最新更新