如何进行验证,以便用户只能输入字母

时间:2016-03-09 11:52:03

标签: python

我正在写这段代码:

import random #this imports the random module
#so I can use this later on to create my randomised numbers.
username=input("What is your name?") #this sets the variable username to
#what the user inputs when asked the question "What is your name?"
print ("Hello " + username) #this then prints hello to the user with the
#username variable so it should say hello with the users name.
questions=0 #this will set the question variable to 0 so I can change
#it later on the script when they get asked a question.
score=0 #this will set the score variable to 0 so i can change it 
#further along the script when they get something right.
while questions < 10:
   num1=random.randint(1,12) #this set the variable num1 to a randomised
   #integar between 0-12,this will be  used in the script for the questions.
    num2=random.randint (1,10) #this will then set the variable num2 to a
    #random number inbetween 1 an 10 which will ,again, be used later on.
    operatorlist= ["-","+","X"] #I made a list of the operators so I can    choose
    #a random item on the list by using the random function.
    operator=random.choice(operatorlist)#this will then choose an random
    actualquestion=(num1, operator, num2, "?")
    #operator from the list
    if operator=="+": #this is a if statement which states that if the operator is
    #add then the answer should be num1 add num2 as the add function was randomly
    #picked

.... 但是如果用户输入他们的名字作为字母,程序就会崩溃。是否有一种简单的方法可以确保用户只输入字母并阻止他们输入其他内容?我不想使用另一个循环函数?我希望它简单,希望只需几行代码。

0 个答案:

没有答案
相关问题