2016-07-01 3 views
0

コンピュータプログラムは、単語が間違って入力されるように単語のスペルミスを処理する方法を教えてください。例えばジェンダーの議論のために男性と女性を入力する。私はこの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の範囲で年齢を強制したいと思います。

+1

ネストした 'while'ループを使ってみましたか? –

+0

ネストされたwhileループで名前が 'Male'または' Female'でないことを確認してから、もう一度 – Li357

答えて

0

有効な入力が得られるまでループを繰り返してください。性別も同じです。

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

他のコードを使用して続行するのではなく、正常に動作せず、最後まで戻ってください。 – kevin

+0

オオプスはタイプミス、上の新しいコードを試してみてください – ifma

0

あなたが満足したい条件を満たすまで続行するwhile演算子を使用してください。

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

「...それが正しくなるまで再入力にそれらを強制的に?...」

あなたも再入力する方法、次のスニペットを求めたので、 \033[<N>Aの形式のエスケープシーケンスmoves the cursor up N linesとのエスケープシーケンス\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()) 

別の解決策は、フォームmoves the cursor backward N columns\033[<N>Dのエスケープシーケンスを使用することです。

関連する問題