Validating correct spelling of user input in Python - python

How would a computer program deal with user misspelling of words in such a way that forces them to reenter until it is correct? e.g. 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.

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?")

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

Related

Output isn't what I expected

I am writing a program using the while loop. I'm trying to write a program to ask the marital status and age of 3 people. The problem I am having is that if I put in an input other than "married", it doesn't add it to the right output. So what I'm asking is how do I make it so that when I put in an input of, for example, "single", the output says, the number of people who are single is: 1?
Here's my code:
marriedstud=0
sepstud=0
marriedover50=0
married40s=0
married30s = 0
married20s = 0
sepover50=0
sep40s=0
sep30s = 0
sep20s = 0
divorcedstud=0
divorcedover50=0
divorced40s = 0
divorced30s = 0
divorced20s = 0
singleover50=0
single40s=0
single30s=0
single20s = 0
singlestud=0
age=0
count = 0
while (count < 2):
maritalstatus= input("Please enter persons marital status:")
age =input("Please enter perons age: ")
if (maritalstatus=="MARRIED") or (maritalstatus=="married"): #I tried using 'and' and 'or' but neither work
marriedstud = marriedstud + 1
if (age>=50):
marriedover50 = marriedover50 + 1
elif (age>=40) and (age<50):
married40s = married40s + 1
elif (age>=30) and (age<40):
married30s = married30s + 1
elif (age>=20) and (age<30):
married20s = married20s + 1
else:
if (maritalstatus=="SINGLE") or (maritalstatus=="single"):
singlestud = singlestud + 1
if (age>=50):
singleover50 = singleover50 + 1
elif (age>=40) and (age<50):
single40s = single40s + 1
elif (age>=30) and (age<40):
single30s = single30s + 1
elif (age>=20) and (age<30):
single20s = single20s + 1
else:
if (maritalstatus=="DIVORCED") or (maritalstatus=="divorced"):
divorcedstud = divorcedstud + 1
if (age>=50):
divorcedover50 = divorcedover50 + 1
elif (age>=40) and (age<50):
divorced40s = divorced40s + 1
elif (age>=30) and (age<40):
divorced30s = divorced30s + 1
elif (age>=20) and (age<30):
divorced20s = divorced20s + 1
else:
if(maritalstatus=="SEPARATED") or (maritalstatus=="separated"):
sepstud = sepstud + 1
if (age>=50):
sepover50 = sepover50 + 1
elif (age>=40) and (age<50):
sep40s = sep40s + 1
elif (age>=30) and (age<40):
sep30s = sep30s + 1
elif (age>=20) and (age<30):
sep20s = sep20s + 1
count += 1
print("The number of pepole who are married is: " +str(marriedstud))
print("The number of pepole who are married and over the 50 is: " +str(marriedover50))
print("The number of pepole who are married and in the age group of 40's is: " +str(married40s))
print("The number of pepole who are married and in the age group of 30's is: " +str(married30s))
print("The number of pepole who are married and in the age group of 20's is: " +str(married20s))
print("*****")
print("The number of pepole who are single is: " +str(singlestud))
print("The number of pepole who are single and over the 50 is: " + str(singleover50))
print("The number of pepole who are single and in the age group of 40's is: " +str(single40s))
print("The number of pepole who are single and in the age group of 30's is: " +str(single30s))
print("The number of pepole who are single and in the age group of 20's is: " +str(single20s))
print("*****")
print("The number of pepole who are divorced is: " +str(divorcedstud))
print("The number of pepole who are divorced and over the 50 is: " +str(divorcedover50))
print("The number of pepole who are divorced and in the age group of 40's is: " +str(divorced40s))
print("The number of pepole who are divorced and in the age group of 30's is: " +str(divorced30s))
print("The number of pepole who are divorced and in the age group of 20's is: " +str(divorced20s))
print("*****")
print("The number of pepole who are separated is: " +str(sepstud))
print("The number of pepole who are separated and over the 50 is: " +str(sepover50))
print("The number of pepole who are separated and in the age group of 40's is: " +str(sep40s))
print("The number of pepole who are separated and in the age group of 30's is: " +str(sep30s))
print("The number of pepole who are separated and in the age group of 20's is: " +str(sep20s))
print("*****")
This is a clash between data types. When the user enters the age after marital status, they enter it as a string, which you cannot compare with integers like 20,30,40, etc. you need to do this:
int(age)
instead of just:
age
please mark as correct if this helps

Name error in Python3 when name is defined [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 years ago.
I am in spyder trying to run a fairly simple python code (python 3.6.4), but when I run the code and use the input statements, it says the names are not defined, even though they should be.
#Module 4 project
#4/25/18
#Henry Degner
#This project is meant to determine whether or not certain people are qualified to go to an exclusive concert
#create function askAge, which will use an input statement and comparison operators to see if the user is old enough
def askAge():
age = int(input("How old are you? "))
if( age >= 18 ):
ageReq = "true"
elif( age < 18 ):
ageReq = "false"
else:
print("Please print you're age with only numerical characters, in years")
age = int(input("How old are you? "))
#create function askHearing, yes or no question to do you have sensitive hearing
def askHearing():
hearing = str(input("Do you have sensitive hearing? "))
if( str(hearing) == "yes","y" ):
hearingReq = "do"
elif( str(hearing) == "no","n"):
hearingReq = "don't"
else:
print("Please type yes, or y, if you have sensitivehearing. If not, type no or n.")
hearing = str(input("Do you have sensitive hearing? "))
#create function askTicket, yes or no question to do you have a ticket
def askTicket():
ticket = str(input("Do you have a ticket for the concert? "))
if( str(ticket) == "yes","y" ):
ticketReq = "do"
elif( str(ticket) == "no","n"):
ticketReq = "don't"
else:
print("Please type yes if you have a ticket, or no if you don't.")
ticketReq = str(input("Do you have a ticket for the concert"))
#create function askFun, yes or no question to are you willing to have an awesome time
def askFun():
fun = str(input("Are you willing to have a great time?"))
if( str(fun) == "yes","y"):
funReq = "do"
elif( str(fun) == "no","n" ):
funReq = "don't"
else:
print("Please type 'yes' or 'no'")
fun = str(input("Are you willing to have a great time?"))
#use def main():
def main():
#print situation, will ask some questions to see if you can attend concert
print("Welcome to the Henry Degner Concert Venue! We have to ask you a few questions before we let you into the venue.")
#use askAge
askAge()
#use askHearing
askHearing()
#use askTicket
askTicket()
#use askFun
askFun()
#print user's answers
print("You said you are " + age + " years old, you " + hearingReq + " have sensitive hearing, you " + ticketReq + " have a ticket, and you " + funReq + " want to have a great time!")
#use if-else statement, if all three conditions match requirements, print you can attend concert. If not, print you can't attend
#use main()
main()
the error outputs as
File "C:/Users/henry/Documents/Current Classes/Foundations of Programming/Module 4 project/Module 4 project script.py", line 60, in main
print("You said you are " + age + " years old, you " + hearingReq + " have sensitive hearing, you " + ticketReq + " have a ticket, and you " + funReq + " want to have a great time!")
NameError: name 'age' is not defined
It also says that all of the other names in line 60 aren't defined. Thanks in advance!
You are getting NameError: name 'age' is not defined because variables from different functions are not shared until you declare them global or you return them from one method to another.
Read more about Python Scopes and Namespaces
Just return value from function to main method.
Returning value from method
def askAge():
age = int(input("How old are you? "))
if( age >= 18 ):
ageReq = "true"
elif( age < 18 ):
ageReq = "false"
else:
print("Please print you're age with only numerical characters, in years")
age = int(input("How old are you? "))
return age
def main():
...
age = askAge()
.....
Same you need to do it for all methods,
askHearing()
askTicket()
askFun()

Having trouble with a List-loop

Basically, you input the names and they are saved to the list. Say I input "a, b, c, d and e. After printing the list it comes out with "a, a, a, a, and a"
Then, when it asks if the student has paid or not, it doesn't matter what value you input, the name won't be moved to the designated list.
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + name + " paid? Input y or n: "
input == raw_input()
if input == "y":
paid_list.append[input]
name_list.next
elif input == "n":
unpaid_list.append[input]
name_list.next
print "The students who have paid are", paid_list
print "The students who have not paid are", unpaid_list
Your populating loop is:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
You first assign the value received through raw_input to name.
Then, for count from 0 to 4, you check if name is equal to the input, and then, append it to name_list.
Instead of checking the equality by writing name == raw_input(...), what you want is to assign the input value into name.
Therefore, you mustn't use ==, but =.
Your loop should be:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
Now here is a more Pythonic way:
names_list = [] # there are more than one name in the list
for _ in range(5): # the loop index is not needed, so I use the anonymous underscore
name = raw_input("Enter the student's name: ")
names_list.append(name)
you can try:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5:
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + names + " paid? Input y or n: "
input = raw_input()
if input == "y":
paid_list.append[input]
elif input == "n":
unpaid_list.append[input]
Note: raw_input() is not there in python 3.x. Instead use: input() (documentation).

create student database in python

I'm a beginner in python. I have created a database for student in python. I'm not able to get the output for all iterations in dict.
my source code:-
n = int(raw_input("Please enter number of students:"))
student_data = ['stud_name', 'stud_rollno', 'mark1', 'mark2','mark3','total', 'average'] for i in range(0,n):
stud_name=raw_input('Enter the name of student: ')
print stud_name
stud_rollno=input('Enter the roll number of student: ')
print stud_rollno
mark1=input('Enter the marks in subject 1: ')
print mark1
mark2=input('Enter the marks in subject 2: ')
print mark2
mark3=input('Enter the marks in subject 3: ')
print mark3
total=(mark1+mark2+mark3)
print"Total is: ", total
average=total/3
print "Average is :", average
dict = {'Name': stud_name, 'Rollno':stud_rollno, 'Mark1':mark1, 'Mark2':mark2,'Mark3':mark3, 'Total':total, 'Average':average} print "dict['Name']: ", dict['Name'] print "dict['Rollno']: ", dict['Rollno'] print "dict['Mark1']: ", dict['Mark1'] print "dict['Mark2']: ", dict['Mark2'] print "dict['Mark3']: ", dict['Mark3'] print "dict['Total']: ", dict['Total'] print "dict['Average']: ", dict['Average']
if i give no of students as 2, I'm getting dict for 2nd database only and not for 1st one too.
output that i got
Please enter number of students:2
Enter the name of student: a
a
Enter the roll number of student:1
1
Enter the marks in subject 1:1
1
Enter the marks in subject 2:1
1
Enter the marks in subject 3:1
1
Total is:3
Average is :1
Enter the name of student:b
b
Enter the roll number of student:2
2
Enter the marks in subject 1:2
2
Enter the marks in subject 2:2
2
Enter the marks in subject 3:2
2
Total is:6
Average is :2
dict['Name']:b
dict['Rollno']:2
dict['Mark1']:2
dict['Mark2']:2
dict['Mark3']:2
dict['Total']:6
dict['Average']:2
Your current code overwrites dict for every i. In addition, you shouldn't use the name dict as this causes confusion with the data type dict in Python.
One solution for you is to use a list of dictionaries, something like the following:
n = int(raw_input("Please enter number of students:"))
all_students = []
for i in range(0, n):
stud_name = raw_input('Enter the name of student: ')
print stud_name
stud_rollno = input('Enter the roll number of student: ')
print stud_rollno
mark1 = input('Enter the marks in subject 1: ')
print mark1
mark2 = input('Enter the marks in subject 2: ')
print mark2
mark3 = input('Enter the marks in subject 3: ')
print mark3
total = (mark1 + mark2 + mark3)
print"Total is: ", total
average = total / 3
print "Average is :", average
all_students.append({
'Name': stud_name,
'Rollno': stud_rollno,
'Mark1': mark1,
'Mark2': mark2,
'Mark3': mark3,
'Total': total,
'Average': average
})
for student in all_students:
print '\n'
for key, value in student.items():
print '{0}: {1}'.format(key, value)
By adding the responses for each new student onto the end of the list, we track all of them in turn. Finally, we print them out using the keys and values stored in the dictionary. This prints, with your inputs:
Name: a
Rollno: 1
Average: 1
Mark1: 1
Mark2: 1
Mark3: 1
Total: 3
Name: b
Rollno: 2
Average: 2
Mark1: 2
Mark2: 2
Mark3: 2
Total: 6
stud = {}
mrk = []
print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")
print("ENTER STUDENT INFORMATION ------------------------ ")
while True :
rno = int(input("enter roll no.. :: -- "))
if rno == 0 :
break
else:
for i in range(3):
print("enter marks ",i+1," :: -- ",end = " ")
n = int(input())
mrk.append(n)
stud[rno] = mrk
mrk = []
print("Records are ------ ",stud)
print("\nRollNo\t Mark1\t Mark2\t Mark3\t Total")
tot = 0
for r in stud:
print(r,"\t",end=" ")
for m in stud[r]:
tot = tot + m
print(m,"\t",end=" ")
print(tot)
tot = 0

Python: Ask user to enter 5 different marks

The question is Write a program that asks the user to enter 5 different students and their mark out of 100. If the user tries to enter a student twice, the program should detect this and ask them to enter a unique student name (and their mark).
my program is..
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
name = raw_input("Enter a unique name: ")
mark = input("Enter the mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary
my problem is how do you loop the else: code if the user keeps entering the same name and mark?
You mix input and raw_input, that's a bad thing. Usually you use raw_input in Python 2 and input in Python 3. The quick and dirty way to solve your problem is:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = raw_input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
print("You already used that name, enter an unique name.")
print dictionary
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
name = name.strip().lower() # store name in lower case, e.g. aamir and Aamir consider duplicate
if not dictionary.get(name):
mark = input("Enter your mark out of 100: ")
dictionary[name] = mark
count += 1
else:
print "please enter unique name"
print dictionary
Store name in lowercase so that aamir and Aamir both should be consider duplicate
the duplicate check should be performed earlier than step Enter your mark to save one step for end user
i think you only need todo this:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary

Categories