Python 如何继续搜索大写字母的循环,直到用户输入正确的输入格式?
这是一个我正在尝试的简单程序。对大写字母的实际搜索效果很好,我的主要问题是,当我运行它时,它只在输入错误后第二次要求输入名字和姓氏,而不做任何其他事情。我希望它无限循环,直到Python 如何继续搜索大写字母的循环,直到用户输入正确的输入格式?,python,regex,loops,iteration,Python,Regex,Loops,Iteration,这是一个我正在尝试的简单程序。对大写字母的实际搜索效果很好,我的主要问题是,当我运行它时,它只在输入错误后第二次要求输入名字和姓氏,而不做任何其他事情。我希望它无限循环,直到isit\u大写==True。我做错了什么 import re def name_get(): global name name = input("First and last name: ") return name name_get() name_search = re.search(r'(.
isit\u大写==True
。我做错了什么
import re
def name_get():
global name
name = input("First and last name: ")
return name
name_get()
name_search = re.search(r'(.*) (.*)', name, re.M)
#separates first and last name
firstcap = name_search.group(1)
lastcap = name_search.group(2)
isit_uppercase = re.search(r'[A-Z]', name) #We want this to be true
lowercase_first = re.search(r'\b[A-Z].*', firstcap) #We want this to be true
lowercase_last = re.search(r'\b[A-Z].*', lastcap) #We want this to be true
#testing that the above code is working properly
print(isit_uppercase, "\n", lowercase_first,"\n", lowercase_last)
def main():
if lowercase_first:
print("Please capitalize your first name!")
name_get()
elif lowercase_last:
print("Please capitalize your last name!")
name_get()
elif isit_uppercase == True:
print("That's a nice name!")
else:
print("Please capitalize your first and last name.")
name_get()
main()
while isit_uppercase == False:
main()
我在谷歌上搜索了很多关于这个特定情况的答案(据我所知)
提前感谢您的想法 好吧,这里发生了很多事情。我建议你在网上做一些编程教程之类的事情,但是下面的更改应该可以解决你的问题,并帮助你的代码看起来更像python 首先,有更好的方法可以做到这一点,正如评论中提到的,并不是所有的名字都以大写字母开头。为了便于说明,也希望是为了教育目的,让我们看看您的代码 基本上,当脚本第一次运行时,您只检查一次大写字母,以后不再检查。在
main
方法中输入并检查:
def main():
name = name_get() # get the name first
# Figure out upper/lowercase
name_search = re.search(r'(.*) (.*)', name, re.M)
#separates first and last name
firstcap = name_search.group(1)
lastcap = name_search.group(2)
isit_uppercase = re.search(r'[A-Z]', name) #We want this to be true
lowercase_first = re.search(r'\b[A-Z].*', firstcap) #We want this to be true
lowercase_last = re.search(r'\b[A-Z].*', lastcap) #We want this to be true
if lowercase_first:
print("Please capitalize your first name!")
elif lowercase_last:
print("Please capitalize your last name!")
elif isit_uppercase == True:
print("That's a nice name!")
else:
print("Please capitalize your first and last name.")
return isit_uppercase # we'll use this to kill our while loop
接下来,使用从main
返回的值中断while循环:
result = False # initialize the value
while result == False:
result = main()
把那个全球的!你几乎从不需要这些
def name_get():
name = input("First and last name: ")
return name
有这样的名字:
Someone von Brauke
。。超过2个单词,其中一些必须是小写。如果您真的需要,请阅读:name=''。join(x.capitalize()表示name中的x.split(“”)
将自动执行此操作…我知道有些名称包含小写字母,这是用于指定格式的赋值。谢谢