我有一个很好用的while语句,我有一整段代码要求用户输入他们有多少名字,然后要求他们输入一个名字的次数,然后每次输入一个名字输入
我需要输入的名称部分被错误点击,但我不知道该怎么做,因为我有一个while语句,我可能需要另外一个while语句,尽管我有错误点击数字名称的部分。
还有一个字典和排序的代码,但我需要帮助与currentnum部分开始的错误点击的一部分
print("Please enter each name when asked without any spaces.") #The program will post this
print("Please enter each of your names individually also.") #Program will again post this
names = [] #This is the value of names which will be changed depending on the input
currentnum = 0 #Currentnum value is 0
while True: #While loop as it will revert to the start if question answered incorrectly
try:
numofnames = int(input("How many names do you have? "))
except ValueError: #if the input is not an integer or a whole number it will
print("Sorry that was not a valid input please retry")
continue #it will loop back and ask the question again as it says that the unput was not valid
else:
break #If the input is correct then the loop will break and continue to the next section of the program
while currentnum < numofnames: #This means that while currentnum is smaller than input for numofnames it will continue to ask question. This is another loop
currentnum = currentnum + 1 # every time the question is asked it means that currentnum gets 1 added to it and will continue to ask untill it is the same as the input for numofnames
name = str(input("Enter your name: ")) #Name asked to be entered in string
name = name.upper() #This changes all letters to upper case no matter what so there is no error for upper and lower case or a bigger dictionary showing lower and upper case values.
names.append(name)
答案 0 :(得分:0)
您的代码对我来说非常好。我没看到用户可以输入哪些可能导致错误的输入,因为python中的大多数数据都可以被串起来并且名称可以是几乎任何东西!如果您可以准确评论可能导致的错误,我可以帮助您
答案 1 :(得分:0)
是的。描述你正在做的最简单的方法是在if语句中使用.isalpha属性。首先,你必须def你的while循环 如下所示:
def Loop():
name_input_complete = False
while name_input_complete != True:
string = input("Please input :")
string = str(string)
if string.isalpha():
name_input_complete = True
else:
print("Please do not use numbers and spaces")
Loop()
Loop()
从根本上说,你必须定义循环,然后运行它。 if语句(这是你应该添加到循环中的部分)然后检查除了字母之外是否还有其他内容。如果为true,则退出错误捕获和循环。该程序继续循环。如果没有则重复while,因为再次调用Loop()函数。