簡體   English   中英

添加到字典時如何使用 while 循環?

[英]How to use a while loop while adding to your dictionary?

我的詞典:

company_account = {
    "CompanyKey": ["Company", "Address", 321321, "City", 14575159920, "Name"]
}

用戶輸入另一個鍵和分配的值:

company_account[input("Enter company key: ")] = input("Enter company name: "), input("Enter company address: "), input("Enter company city code: "), input("Enter city: "), ---> ID <---, input("Enter owners name: ")

While 循環限制用戶只能輸入len == 11的數字

while True:
    ID = input("Enter companys ID: ")
    if len(ID) == 11:
        print(ID)
        break
    else:
        print("ID has to have 11 digits. Try again.")

我的問題是:如何將這個 while 循環放在更新字典的company_account中,而不是ID中? 或者也許是其他一些解決方案來限制用戶在更新字典時輸入恰好 11 位數字的數字?

我嘗試放置global ID ,但它返回錯誤。

您獲取輸入的循環很好。 只需將其設為函數並使用它代替鍵分配中的標准input

def get_id():
    while True:
        ID = input("Enter companys ID: ")
        if len(ID) == 11:
            return ID
        else:
            print("ID has to have 11 digits. Try again.")

company_account[input("Enter company key: ")] = [input("Enter company name: "), ..., get_id(), ...]

是這樣的嗎? 使您的 len-check 成為一個功能,並提出您的問題並將它們放入字典中。 如果你問我,更容易閱讀。

還添加到 check_len 函數以確保輸入是 int。 對城市代碼也一樣。


def check_len(description):
    while True:
        ID = input(description)
        if len(ID) == 11:
            try:
                return int(ID)
            except ValueError:
                print('ID can only contain digits.')
        else:
            print("ID has to have 11 digits. Try again.")

def check_int(description):
    while True:
        ID = input(description)
        try:
            return int(ID)
        except ValueError:
            print('ID can only contain digits.')


a = check_len('Enter Company key: ')
b = input('Enter Company name: ')
c = input('Enter Company address: ')
d = check_int('Enter Company City Code: ')
e = input('Enter City: ')
f = input('Enter owners name: ')

company_account = {
    "CompanyKey": [a, b, c, d, e, f]
}

print(company_account)

輸出:

Enter Company key: 12345678910
Enter Company name: Useless Apps
Enter Company address: Useless Street
Enter Company City Code: 1337
Enter City: Useless Town
Enter owners name: Mr Useless
{'CompanyKey': [12345678910, 'Useless Apps', 'Useless Street', 1337, 'Useless Town', 'Mr Useless']}

不過,我肯定會建議您查看類和對象。

錢幣。 你正在用鋼鋸砍樹。 我們需要給你買些電動工具!

我會給你一些“香草”Python 3.6+ 的東西,同時提到有第三方庫可以幫助你。

class CompanyAccount:
    
  def __init__(self):
    self.key=self.ask_for("key")
    self.name=self.ask_for("name")
    self.address=self.ask_for("address")
    self.city_code=self.ask_for("City Code")
    self.city=self.ask_for("City")
    self.owner=self.ask_for("owner's name")

    self.id=self.ask_for_id()

  @staticmethod
  def ask_for_id():
    while True:
      ID = self.ask_for("ID")
      if len(ID) == 11:
        break
      else:
        print("ID has to have 11 digits. Try again.")
    # break out of loop here
    return ID

  @staticmethod
  def ask_for(val):
    return input(f"Enter Company {val}: ")

  def to_dict(self):
    return {
      self.key: [
        self.name,
        self.address,
        self.city_code,
        self.city,
        self.id,
        self.owner,
      ]
    }

# initialise
company = CompanyAccount()

print(company.id) # etc.

company.to_dict() # in case the format you asked for is really important

暫無
暫無

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

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