简体   繁体   中英

How to use a while loop while adding to your dictionary?

My dictionary:

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

User input of another key and values assigned:

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 loop that restricts the user to only enter a number that's 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.")

My question is: how can I put this while loop in company_account that updates the dictionary, instead of ID ? Or maybe some other solution to restricting the user to enter a number that's exactly 11 digits long while updating the dictionary?

I tried putting global ID , but it returns an error.

Your loop for getting the input is good. Just make it a function and use it instead of the standard input in the key assignment:

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(), ...]

Something like this? Made your len-check a function and took your question af and put them in the dict. Easier to read if you ask me.

Also added to check_len function to make sure the input is int. Did same for city code.


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)

Output:

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']}

I'd definitely recommend you to look into Classes and Objects though.

Oof. You're chopping down a tree with a hacksaw. We need to get you some power tools!

I'll give you something in 'vanilla' Python 3.6+, while mentioning that there are third party libraries out there that can help you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM