How would a computer program deal with user misspelling of words in such a way that forces them to reenter until it is correct? eg Entering Male and Female for a gender argument. I'm using this Python code:
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)
I would like to also force an age in the 18-25 range.
"... that forces them to reenter until it is correct?... "
Since you also asked for a way to re-enter, the following snippet uses an escape sequence of the form \\033[<N>A
which moves the cursor up N lines and the Carriage Return escape sequence, \\r
, to print over the invalid data and take input again.
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())
Another solution would be to use the escape sequence of the form \\033[<N>D
which moves the cursor backward N columns .
Just keep looping until they give a valid input. Do the same for the gender.
Age = ""
while True:
Age = int(input('How old are they?'))
if int(Age) >= 18 and int(Age) <= 25:
break
Simply use a while operator that continues until you have satisfied the condition you wish be satisfied.
Gender = ""
while Gender != "Male" or Gender != "Female":
Gender = raw_input("What is your gender, Male or Female?")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.