【问题标题】:Restarting loop to iterate over a user string [duplicate]重新启动循环以迭代用户字符串[重复]
【发布时间】:2019-08-01 06:05:57
【问题描述】:
我正在尝试接受用户输入并检查字符串中的非字母值。我的问题是如果他们输入了错误的值,我该如何再次查询它们并重新开始循环?见下文
name = str(input("Enter name:"))
for i in name:
if not i.isalpha():
name = str(input("Enter name:")
**line to start iterating from the beginning with new entry.**
只是试图验证用户只输入字母。如果检查失败,他们会再次输入名称并重新开始。提前致谢!
【问题讨论】:
标签:
python
python-3.x
loops
for-loop
【解决方案1】:
你可以这样做:
correct = False
while correct == False:
name = str(input("Enter name:"))
for i in name:
if not i.isalpha():
correct = False
break
else:
correct = True
【解决方案2】:
您可以在下面看到一个示例代码:
while True:
number_found = False
name = str(input("Enter name:"))
for i in name:
print("Check {} character".format(i))
if i.isdigit():
print("{} is number. Try again.".format(i))
number_found = True
break # Break the for loop when you find the first non-alpha. You can reduce the run-time with this solution.
if not number_found:
break
print("Correct input {}".format(name))
输出:
>>> python3 test.py # Success case
Enter name:test
Check t character
Check e character
Check s character
Check t character
Correct input test
>>> python3 test.py # Failed case
Enter name:test555
Check t character
Check e character
Check s character
Check t character
Check 5 character
5 is number. Try again.
Enter name: