Just a few observations, hope you don't mind:
1) Python has True = 1 and False = 0 builtin
2) define your functions outside of the conditional if, or Python will redefine your functions whenever you take a test. This would slow down the program. The memory manager cleans up properly though.
3) use a try/except to protect against non numeric entries
Here is the code sample updated:
#true = 1 # Python has True = 1
#false = 0 # Python has False = 0
def get_questions(x = -1):
lista = [["What colour is the daytime sky on a clear day?","blue"],
["What is the answer to life, the universe and everything?","42"],
["What is a three letter word for mouse trap?","cat"],
["What noise does a truly advanced machine make?","ping"]]
if x == -1:
return lista
else: #of course, it's recommended to check if x is out of bounds
return lista[x]
def check_question(question_and_answer):
question = question_and_answer[0]
answer = question_and_answer[1]
given_answer = raw_input(question)
if answer == given_answer:
print "Correct"
return True
else:
print "Incorrect, correct was: ",answer
return False
def run_test(questions):
if len(questions) == 0:
print "No questions were given."
return
index = 0
right = 0
while index < len(questions):
if check_question(questions[index]):
right = right + 1
index = index + 1
print "You got ", right*100/len(questions),"% right out of",len(questions)
menu_item = 0
while menu_item != 9:
print "------------------------------------"
print "1. Take test"
print "2. Display all questions and answers."
print "9. quit"
try:
menu_item = input("Pick an item from the menu: ")
except:
# protect against just enter or not numeric
print '-' * 36
print "Need integer input!"
# pick a non existing menu_item to start at top of while loop
menu_item = 3
if menu_item == 1:
run_test(get_questions())
elif menu_item == 2:
index = 0
length_quest = len(get_questions())
if length_quest > 0:
while index < length_quest:
print 'Question: ', get_questions(index)[0],
print 'Answer: ', get_questions(index)[1]
index = index + 1
else:
print "No questions"
print "Goodbye."
Great quiz program though, I love it! Python is a fun language to learn!
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
Maybe this will help you ...
import time
print time.ctime() # Sat Sep 02 18:23:53 2006
# get just hr, min, sec of present time tuple
hr, min, sec = time.localtime()[3:6]
print hr, min, sec # 18 23 53
print sec, type(sec) # 53 <type 'int'>
# if you just want seconds
sec = time.localtime()[5]
print sec # 53
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Since you want to save and later load an entire container object, the module pickle is what you want to use. Hre is a simple example:
# pickle saves and loads any Python object intact
# via a byte stream, use cpickle for higher speed
import pickle
myList1 = [12, 52, 62, 02, 3.140, "Monte"]
print "Original list:"
print myList1
file = open("list1.dat", "w")
pickle.dump(myList1, file)
file.close()
file = open("list1.dat", "r")
myList2 = pickle.load(file)
file.close()
print "List after pickle.dump() and pickle.load():"
print myList2
In your case you would pickle the students dictionary!
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
What does your student dictionary look like just before you pickle.dump() it?
Also, you could write a small Python program that pickle.load() that file and looks at its contents.
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Watch out when you start your program that your basic students dictionary does not override the newly loaded dictionary. Here is your code sample that works:
import pickle
max_points = [25,25,50,25,100]
assignments = ["hw ch 1","hw ch 2","quiz ","hw ch 3","test"]
try:
file = open("students.dat", "r")
students = pickle.load(file)
file.close()
except:
students = {"#Max":max_points}
print "students.dat file not found, starting with", students
def print_menu():
print "1. Add student"
print "2. Remove student"
print "3. Print grades"
print "4. Record grade"
print "5. Exit"
def print_all_grades():
print "\t",
for i in range(len(assignments)):
print assignments[i],"\t",
print
keys = students.keys()
keys.sort()
for x in keys:
print x,"\t",
grades = students[x]
print_grades(grades)
def print_grades(grades):
for i in range(len(grades)):
print grades[i],"\t\t",
print
print_menu()
menu_choice = 0
while menu_choice != 5:
print
menu_choice = input("Menu Choice (1-6): ")
if menu_choice == 1:
name = raw_input("Student to add: ")
students[name] = [0]*len(max_points)
elif menu_choice == 2:
name = raw_input("Student to remove: ")
if students.has_key(name):
del students[name]
else:
print "Student: ",name," not found"
elif menu_choice == 3:
print_all_grades()
elif menu_choice == 4:
print "Record Grade"
name = raw_input("Student: ")
if students.has_key(name):
grades = students[name]
print "Type the number of the grade to record"
print "Type a 0 (zero) to exit"
for i in range(len(assignments)):
print i+1," ",assignments[i],"\t",
print
print_grades(grades)
which = 1234
while which != -1:
which = input("Change which Grade")
which = which-1
if 0 <= which < len(grades):
grade = input("Grade: ")
grades[which] = grade
elif which != -1:
print "Invalid Grade Number"
else:
print "Student not found"
elif menu_choice != 5:
print_menu()
print students # test
# update students.dat file upon exit
file = open("students.dat", "w")
pickle.dump(students, file)
file.close()
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
Good! The try/except is part of error checking you will tackle next.
What it does in the above code is the following, it tries to load the data file, if there is an error like a missing data file, it does the except part. In the except part you can be more specific about the exact error. Well anyway, have fun learning Python.
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213