簡體   English   中英

如何循環 python 列表輸入驗證?

[英]How do I loop a python list input validation?

newcompany = input("Enter Company Name: ")
for stock in portfolioStock:
    if newcompany.lower() == stock[0].lower():
        newcompany = input("Company already exist in the Portfolio\nPlease 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 Portfolio\nPlease 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

它在三星下方留下一個空格,並且不會繼續到下一行代碼

我不完全清楚你在找什么。 假設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 Portfolio\nPlease 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 Portfolio\nPlease enter another Company Name: ")

portfolioStock.append(company.capitalize())

謝謝米切爾·奧利斯拉格斯!!

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

因為我的投資組合股票是一個包含 str 和 int 的 2D 列表,所以我不得不稍微編輯 Mitchell 的代碼,但它可以工作!!! 太感謝了!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM