0

我需要帮助包裹:

if any(c.isdigit() for c in name):
print("Not a valid name!")

在 while 语句中。这几乎只是读取“名称”变量的输入并查看其中是否有整数。我怎么能在 while 语句中使用它?我只是希望它是如果用户在输入中输入一个变量,它将打印出上面的字符串并循环回来并再次询问用户他们的名字,直到他们成功输入一个没有整数的字符串,然后我想要它打破。有什么帮助吗?

print("Hello there!")
yn = None
while yn != "y":
    print("What is your name?")
    name = raw_input()
    if any(c.isdigit() for c in name):
        print("Not a valid name!")
    print("Oh, so your name is {0}? Cool!".format(name))
    print("Now how old are you?")
    age = raw_input()
    print("So your name is {0} and you're {1} years old?".format(name, age))
    print("y/n?")
    yn = raw_input()
    if yn == "y":
        break
    if yn == "n":
        print("Then here, try again!")
print("Cool!")
4

3 回答 3

1

输入有效名称后,使用while Trueand abreak结束循环:

while True:
    name = raw_input("What is your name? ")
    if not any(c.isdigit() for c in name):
        break
    print("Not a valid name!")

这比首先初始化name无效的东西然后在测试中使用any()表达式要容易得多。while

于 2013-05-09T18:11:48.730 回答
0

你只是说你想要一个continue后你的print("Not a valid name!")

print("Hello there!")
yn = None
while yn != "y":
    print("What is your name?")
    name = raw_input()
    if any(c.isdigit() for c in name):
        print("Not a valid name!")
        continue
    print("Oh, so your name is {0}? Cool!".format(name))
    ...

continue只会回到循环的顶部。

于 2013-05-09T18:19:11.200 回答
0

像这样的东西:

name = input("What is your name? : ")
while any(c.isdigit() for c in name): 
    print ("{0} is invalid, Try again".format(name))
    name = input("What is your name? : ")

演示:

What is your name? : foo1
foo1 is invalid, Try again
What is your name? : 10bar
10bar is invalid, Try again
What is your name? : qwerty
于 2013-05-09T18:13:11.103 回答