2017-02-19 64 views
-1

我有一个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) 
+2

快速的问题。 “点击错误”是什么意思? – Kevin

+0

像这样,如果有人把数字或什么东西,我不想让他们然后程序将关闭,并说你只能在这种情况下放在字母 –

回答

0

是的。描述你在做什么的最简单的方法是在if语句中使用.isalpha属性。首先,你将有你的变形点焊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()  

Baisically你必须定义循环,然后运行它。 if语句(这是你应该添加到循环中的部分)然后检查除了字母之外什么都没有。如果为true,则完成错误陷印和循环。该程序在循环之外继续。如果不是,则重复一次,因为再次调用Loop()函数。

+0

好的,我会在代码中的names.append后面加上那个。什么是做什么部分我如何让它继续与代码,如果它是全部字母,如果它不结束代码说不使用空格和数字? –

+0

我很抱歉。我想我做错了什么。我将编辑我的答案,以便它显示写入代码 – 2017-02-19 19:27:11

+0

非常感谢你,它的工作原理非常好,唯一的问题是下面的Loop()意味着它循环请不要多次使用空格和数字,并且不会给oppurtunity循环回去,然后再次询问名字,但这对我将要实现的内容并不重要。我只是设置它,以便如果他们使用空格或数字,那么程序将关闭。 :) –

0

你的代码看起来对我非常好。我没有看到用户可以输入什么输入,这可能会导致一个错误,因为python中的大多数数据都可以是串并且名称可以是任何东西!如果你可以评论究竟什么错误可能会导致我可能能够帮助你

+0

像我不想要那里有数字或空格只输入字母那是.salpha? –