繁体   English   中英

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

[英]Validating correct spelling of user input in 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岁之间。

“……迫使他们重新进入,直到正确为止?……”

由于您还要求重新输入方法,因此以下代码段使用\\033[<N>A ”格式的转义序列将光标向上移N行,并使用回车转义序列\\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形式的转义序列, 该游标将光标向后移动N列

只要保持循环,直到他们提供有效的输入。 对性别也做同样的事情。

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

只需使用一会儿继续的运算符,直到您满足希望满足的条件为止。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM