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

2024-03-28 18:54:12 发布

您现在位置:Python中文网/ 问答频道 /正文

计算机程序如何处理用户拼错的单词,迫使他们重新输入直到正确为止?e、 为性别争论输入男性和女性。我使用的是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岁之间。在


Tags: thetonameinputageispeoplelength
3条回答

一直循环,直到他们给出有效的输入。对性别也一样。在

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

"... that forces them to reenter until it is correct?... "

由于您还要求一种重新输入的方法,下面的代码片段使用格式为\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形式的转义序列moves the cursor backward N columns。在

只需使用while运算符,该运算符将一直持续到满足您希望满足的条件。在

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

相关问题 更多 >