I am trying to figure out how to create a sentinel code to allow the user to input a name and test score that will be listed in a text file. I just need the names to be in column one and scores in column two of the text file. I tried having the name and grade as a single input but was given errors. I am still getting an error for the code below.
Enter the students’ name and test score. Store entered data in a text file named Class.txt, and close the file. Use an empty string as a sentinel to stop the data entry. Make sure that program will accept only correct data for the student’s test scores.
def main():
outfile = open("Class.txt", 'w')
count = 0
student = input("Please enter a student's last name (<Enter> to quit): ")
grade = eval(input("Please enter the student's grade (<Enter> to quit): "))
while student != "" and grade != "":
count = count + 1
student = input("Please enter a student's last name (<Enter> to quit): ")
grade = eval(input("Please enter the student's grade (<Enter> to quit): "))
print(student, grade, file = outfile)
outfile.close()
main()
error:
grade = eval(input("Please enter the student's grade (<Enter> to quit): "))
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
You are sending an un-sanitized user input to eval - this is a very unsafe practice, and it is also what's causing an error when you try to use the sentinel (empty input for grade). You should not really be asking for grade if the name is empty.
To avoid repetition, you should place you should place your input calls in a function:
def get_data():
student = input("Please enter a student's last name (<Enter> to quit): ")
if student:
grade = input("Please enter the student's grade (<Enter> to quit): ")
if grade.isdigit():
return (student, int(grade))
return (None, None)
I added an implicit sentinel - if grade is not an natural number, then the loop will stop, too.
Then, you loop would look like this:
(student, grade) = get_data()
while student:
print(student, grade, file = outfile)
(student, grade) = get_data()
Note that I swapped the order of the input and output in the main loop, since in your original code the first input would have not been processed.
Related
I want to create a simple app to Ask user to give name and marks of 10 different students and Store them in dictionary.
so far only key:value from the last input is stored into dictionary.
can you please check my code?
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks = {student_name.title():student_mark}
print(marks)
Your current code has two issues: first, it doesn't save the values of each student inside the loop. Second, it always rewrites the entire dictionary with a single key/value pair, that's why it doesn't work.
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks[student_name.title()] = student_mark
print(marks)
You need your code to be inside your loop. Also the way you put value inside your dict is not right. This should do the trick
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks[student_name] = student_mark
print(marks)
I have been working on this for too long. It should be simple and I've ran through many different combinations, however, I keep getting the code wrong and have no idea why. It works fine when I have manual input, but when I submit there is an error.
question prompt:
Write a program that keeps a dictionary of names and their corresponding phone numbers.
Repeatedly ask the user for a name. Then, do one of the following three things, depending on what they enter:
If they enter nothing, exit the program.
If they enter a name that exists as a key in your dictionary, simply print the corresponding phone number.
If they enter a name that is NOT in your dictionary as a key, ask the user for a phone number, and then put the name and phone number in your dictionary.
Print out the final dictionary.
my code:
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
if not name in phoneBook:
number = input("Please enter number: ")
print "Phone number: " + number
phoneBook[name] = number
name = input("Please enter a name(or press enter to end input): ")
if name in phoneBook:
print phoneBook[name]
if name == '':
break
print phoneBook
Expected result:
Phone number: 1234
Phone number: 5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
My result:
Phone number: 1234
Phone number: 5678
Phone number: 9999
1234
Phone number: 9999
5678
Phone number: 9999
{'Tracy': '9999', 'Karel': '9999', 'Steve': '9999'}
you must also access the dictionary keys for checking the existence of a name:
if not name in phoneBook.keys():
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
if not name in phoneBook.keys():
number = input("Please enter number: ")
phoneBook[name] = number
print "Phone number: " + number
name = input("Please enter a name(or press enter to end input): ")
else:
print phoneBook[name]
print phoneBook
Try the above code.
When a name is not in the phoneBook, then assign the name a number, so phoneBook[name] = number should be in the if not name in phoneBook.keys(): block. And then enter another name in the same if block.
I have some code:
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
How can I keep asking for the player's name until they enter a name that is more than one character long, and tell them they must enter a valid name if they leave the field blank?
I tried
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
while len(PlayerName) < 1:
print("You must enter a name!")
but have been unsuccessful.
Use a while loop to get the input repetitively:
def get_player_name():
print()
player_name = ""
while len(player_name) <= 1:
player_name = input('Please enter your name: ')
print()
return player_name
The way you are currently using it, you use the while statement to only print the error message.
PS: I've converted your variable names etc to small_caps_format because that is what PEP recommends.
def GetPlayerName():
print()
while True:
PlayerName = input('Please enter your name: ')
if len(PlayerName) > 1:
break
print("Your name is too short! :c")
print()
return PlayerName
One solution amongst others, and doesn't require any variables outside of the while loop. As mentioned by #jme, the error message is rather easy to print with this solution. The issue with your code is that:
Your while loop is after the return statement is called, so it's affectively rendered mute.
Your while loop is infinite-- it doesn't give the user a chance to re-try!
I have this program, and it is almost perfect but I need the dictionary to print on separate lines like so:
Please enter a name (or just press enter to end the input): Tom
Please enter Tom's phone: 555-5555
Please enter a name (or just press enter to end the input): Sue
Please enter Sue's phone: 333-3333
Please enter a name (or just press enter to end the input): Ann
Please enter Ann's phone: 222-2222
Please enter a name (or just press enter to end the input):
Thank you.
Your phonebook contains the following entries:
Sue 333-3333
Tom 555-5555
Ann 222-2222
Here is my code:
def main():
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
number = input("Please enter number: ")
phoneBook[name] = number
name = input("Please enter a name(or press enter to end input): ")
if name == '':
print("Thank You!")
print("Your phonebook contains the following entries:\n",phoneBook)
main()
Loop through the entries in your phonebook and print them one at a time:
for name, number in phoneBook.items():
print ("%s %s" % (name, number))
something like this:
strs = "\n".join( " ".join((name,num)) for name,num in phoneBook.items() )
print("Your phonebook contains the following entries:\n",strs)
if you dont want to write codes yourself, pprint could be an option:
import pprint
....
print("Your phonebook contains the following entries:\n")
pprint.pprint(phoneBook)
You can use format() to make your life easy:
for i in phoneBook.iteritems():
print("{0} {1}".format(*i))
my_dictionary = {}
while True:
name = str(input("Enter a name: "))
if name == "":
break
elif name in my_dictionary:
print "Phone Number: " + my_dictionary[name]
else:
phone_number = input("Enter this person's number: ")
my_dictionary[name] = phone_number
print my_dictionary
Firstly, I am new to Python so please go easy on me... Secondly, I've never used a forum before so if I paste too much code or don't give exactly what you need, forgive me, I shall try my best:
WHAT I NEED MY CODE TO DO:
I need my code to ask the user for an input called moduleName then after moduleName is entered I need it to ask the user for the grade for that specific module. After that is entered I need it to ask again for module then the grade until there are no more to enter where by the user will enter -1 into the module bit to end it. I also need each item to save to a global list I have created. So when I use teh function I have created to view the list it prints out all modules and grades.
MY CODE THUS FAR: (my global list is at top of code named students[])
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
**moduleName= 0
while moduleName != "-1":
moduleName = raw_input("Please enter module name: ")
grade = raw_input ("Please enter students grade for " + moduleName+": ")
students.append(student)**
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
THE OUTPUT I GET:
I have now fixed the loop so it breaks correctly... the only problem I have now is that the moduleName and grade fields save to my global list but only save the last input (being -1) as opposed to the multiple inputs entered... so confused.
The problem may also lie within this function I have created:
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
Again apologies I don't know what's needed on forums etc so go easy on me...
Thank in Advance! =D
I would suggest replacing the while moduleName != "-1": loop with a while True: loop, and then insert this code after asking for the module name:
if moduleName == '-1':
break
This will break out of the while loop when you want it to.
Addressing your second question, the append function is in the else bit of the whole while loop. This means that it only works when the function breaks. You need to put this in the main while loop after you get the input, and get rid of the else.
Also, I don't see student defined anywhere - what is it meant to be?
Here's the code you want:
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == '-1':
break
grade = raw_input("Please enter students grade for " + moduleName+": ")
students.append(student)