我试图循环我的代码,以便如果输入无效,它将继续循环

时间:2018-04-03 13:25:28

标签: python-3.x

是否有办法循环此代码,以便它继续要求正确的输入。我是python的新手并且到目前为止这是一个奇迹

亲切的问候 Harrry

   import re

r = re.compile(r'[a -z A -Z]')
print("Welcome to this questionnaire:")
x = input("Your Name:")

while not r.match(x):
    print("Come on,'", x, "' can't be your name")
    x = input("Your Name:")

if 3 <= len(x) <= 10:
    print("Hi,", x, "!")
elif len(x) > 10:
    print("Mmm,Your name is too long!")
elif len(x) < 3:
    print("Sorry, your name is too short!")

1 个答案:

答案 0 :(得分:0)

尝试:

import re

r = re.compile(r"^[A-Za-z]*$")        #Match only alpha
print("Welcome to this questionnaire:")
x = input("Your Name:")

while not r.match(str(x)):
    print("Come on,'", x, "' can't be your name")
    x = input("Your Name:")

或者您可以使用str.isalpha

print("Welcome to this questionnaire:")
x = input("Your Name:")
while not str(x).isalpha():
    print("Come on,'", x, "' can't be your name")
    x = input("Your Name:")