是否可以重用“if”语句?

时间:2015-07-15 19:36:05

标签: python if-statement console code-reuse reusability

所以我正在研究一个项目,我想知道是否可以重用'if'语句。例如,我现在的代码是

import re
import string
userinput=''
print "Hello! What is your name?"

userinput = str(raw_input("My name is "))

if not re.search(r'[A-Za-z]', userinput):
    print "That isn't a name!"
    print str(raw_input("My name is "))

并打印

Hello! WHat is your name?
My name is 86124674983@
That isn't a name! 
My name is 986421674941
986421674941

正如您所看到的,它将除字母之外的任何内容识别为无效入口,但它只会执行一次。如果您第二次输入符号时会提示您输入名称,则会接受该随机输入并将其打印出来。我想要它打印

Hello! WHat is your name?
My name is 86124674983@
That isn't a name! 
My name is 986421674941
That isn't a name! 
My name is Eli

对不起,如果这让任何人感到困惑。如果您需要澄清任何内容,请不要犹豫。非常感谢提前!!

2 个答案:

答案 0 :(得分:2)

使用while循环:

print "Hello! What is your name?"
while True:
    userinput = raw_input("My name is ")
    if not re.search(r'[A-Za-z]', userinput):
        print "That isn't a name!"
    else:
        break

print userinput

请注意,您不要print raw_input() - 或将其设为str(已经是)。您所需要的只是raw_input('text'),它会显示text

答案 1 :(得分:0)

使用while循环:

print "Hello! What is your name?"
while True:
    userinput = raw_input("My name is ")
    if re.search(r'[A-Za-z]', userinput):
        break
    print "That isn't a name!"
print userinput