在Python中验证用户输入的正确拼写

时间:2016-07-01 19:02:30

标签: python

计算机程序如何以一种强制它们重新进入直到正确的方式处理用户拼写错误的单词?例如输入男性和女性进行性别争论。我正在使用这个Python代码:

def mean(values):

    length = len(values)

    total_sum = 0
    for i in range(length):
        total_sum += values[i]

    total_sum = sum (values)
    average = total_sum*1.0/length
    return average

name = " "
Age = " "
Gender = " "
people = []
ages = []
while  name != "":

### This is the Raw data input portion and the ablity to stop the program    and exit
    name = input("Enter a name or type done:")
    if name == 'done' : break
    Age = int(input('How old are they?'))

  Gender = input("What is their gender Male or Female?")


### This is where I use .append to create the entry of the list     
people.append(name)
people.append(Age)
ages.append(Age)
people.append(Gender)
### print("list of People:", people)

#### useing the . count to call how many  m of F they are in the list 

print ("Count for Males is : ", people.count('Male'))
print ("Count for Females is : ", people.count('Female'))

### print("There ages are",ages)

### This is where I put the code to find the average age

x= (ages)

n = mean(x)

print ("The average age is:", n)

我还想强迫年龄在18-25岁之间。

3 个答案:

答案 0 :(得分:1)

  

“......迫使他们重新进入直到它正确?......”

由于您还要求重新输入,因此以下代码段使用\033[<N>A格式moves the cursor up N linesCarriage Return转义序列\r的转义序列},打印无效数据并再次输入。

import sys

age = 0
gender = ""

agePrompt = "How old are they? "
genderPrompt = "What is their gender Male or Female? "

#Input for age
print("")
while not ( 18 <= age <= 25 ):
    sys.stdout.write( "\033[1A\r" + " " * (len(agePrompt) + len(str(age))) )
    sys.stdout.write( "\r" + agePrompt )
    sys.stdout.flush()
    age=int(input())

#Input for gender
print("")
while not ( gender == "Male" or gender == "Female" ) :
    sys.stdout.write( "\033[1A\r" + " " * (len(genderPrompt) + len(str(gender))) )
    sys.stdout.write( "\r" + genderPrompt )
    sys.stdout.flush()
    gender=str(input())

另一种解决方案是使用\033[<N>D {{1}}形式的转义序列。

答案 1 :(得分:0)

只需保持循环,直到它们给出有效输入。为性别做同样的事情。

Age = ""
while True:
  Age = int(input('How old are they?'))
  if int(Age) >= 18 and int(Age) <= 25:
    break

答案 2 :(得分:0)

只需使用while运算符,直到您满意您满意的条件为止。

 Gender = ""
    while Gender != "Male" or Gender != "Female":
        Gender = raw_input("What is your gender, Male or Female?")