我基本上是运行一个代码,通过用户条目将地址簿构建到文本文件中。
在这样做的同时,我正在检查输入的信息是否正确,如果不是,则要求他们更正。但是,我意识到用户可以无限次地输入不正确的信息(尽管不太可能),所以我希望实现一个“while”循环来解决这个问题。
在下面的代码的情况下,我基本上试图让它,而不是第一个ifelse条目,我可以通过检查“First_Name.isalpha():”的布尔值进入循环。但是,当“First_Name.isalpha():”为真时,我无法想到进入它的方法,因为条目正确,我不需要进入循环。当它为假时,我们完全跳过循环而不更正条目。
这基本上提示了一个问题,即当布尔值为false时是否有进入循环的方法。或者,如果还有另一个我不考虑的创意解决方案。
谢谢,
新手编码器
NewContact = "New Contact"
def NewEntry(NewContact):
# Obtain the contact's information:
First_Name = input("Please enter your first name: ")
Last_Name = input("Please enter your last name: ")
Address = input("Please enter your street address: ")
City = input("Please enter your city of residence: ")
State = input("Please enter the 2 letter abbreviation of your state of residence: ")
ZipCode = input("Please enter your zip code: ")
Phone_Number = str(input("Please enter your phone number: "))
# Ensure all information inputted is correct:
if First_Name.isalpha():
First_Name = First_Name.strip()
First_Name = First_Name.lower()
First_Name = First_Name.title()
else:
First_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
if Last_Name.isalpha():
Last_Name = Last_Name.strip()
Last_Name = Last_Name.lower()
Last_Name = Last_Name.title()
else:
Last_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
# Organize inputted information:
NewContact = Last_Name + ", " + First_Name
FullAddress = Address + " " + City + ", " + State + " " + ZipCode
# Return information to writer to ensure correctness of information
# Write information onto document
TheFile = open("AddressBook", "w")
TheFile.write(str(NewContact) + "\n")
TheFile.write(str(FullAddress) + "\n")
TheFile.write(str(Phone_Number) + "\n")
TheFile.close()
NewEntry(NewContact)
答案 0 :(得分:3)
您正在寻找not
运算符,它会反转一个布尔值:
>>> not False
True
>>> not True
False
>>> not "".isalpha()
True
>>> not "abc".isalpha()
False
您可以在任何表达if
或while
的有效条件的前面加上它。
答案 1 :(得分:-1)
使用此结构
invalid = True
while invalid:
## get inputs
## validate inputs
## set invalid accordingly