如何使用while循环,同时添加到您的字典?



我的字典:

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

你在用钢锯砍树。我们得给你弄些电动工具来!

我将给你一些'香草' 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

像这样?把你的镜头检查变成一个函数,把你的问题a-f放进字典里。如果你问我的话,更容易读。

也添加到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']}

我强烈建议你看看类和对象。

相关内容

  • 没有找到相关文章

最新更新