我需要帮助包装:
if any(c.isdigit() for c in name):
print("Not a valid name!")
在while语句中。这几乎只是读取“name”变量的输入,并查看其中是否有整数。我怎么能在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!")
答案 0 :(得分:1)
使用while True
和break
在输入有效名称时结束循环:
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
表达式更容易。
答案 1 :(得分: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
答案 2 :(得分: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
只会回到你的循环顶部。