It is very annoying, I have typed it as best I can, but option 2 doesn't work. Option 1 is to take the test in Test.py, option 9 is to quit, and option 2 is supposed to print all the questions and answers. This is the code:

true = 1
false = 0
def get_questions():
    return[["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"]]
menu_item = 0
while menu_item != 9:
    print "------------------------------------"
    print "1. Take test"
    print "2. Display all questions and answers."
    print "9. quit"
    menu_item = input("Pick an item from the menu: ")
    if menu_item == 1:
        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)
        run_test(get_questions())
        
    elif menu_item == 2:
        current = 0
        if len(get_questions) > current:
            while current < len(get_questions(index)):
                index=current
                print current,". ",get_questions(current)
                current = current + 1
        else:
            print "No questions"
print "Goodbye."

Here is the error message when I type "2" into the option selection:

Traceback (most recent call last):
File "C:\Python24\test", line 45, in -toplevel-
print current,". ",get_questions(current)
TypeError: get_questions() takes no arguments (1 given)

What is wrong with my program and how do I fix it?

Well, you have defined function get_questions() not to take any arguments, but in lines:

while current < len(get_questions(index)):

and

print current,". ",get_questions(current)

you're passing argument to it.
If you want your function to deal with arguments, you need to define it that way.

I would do something like this ( I reserve right to be completely wrong ;) ):

true = 1
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]
      
menu_item = 0
while menu_item != 9:
    print "------------------------------------"
    print "1. Take test"
    print "2. Display all questions and answers."
    print "9. quit"
    menu_item = input("Pick an item from the menu: ")
    if menu_item == 1:
        def check_question(question_and_answer):
            question = question_and_answer[0]
            answer = question_and_answer[1]
            given_answer = raw_input(question) #what if user just press Enter?
            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)
        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."

Thank you sooo much. Now for the next section!

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!

I need help now making the HiLo game use the last two digits of the current time. Once I've imported the time module, what then? I know how to get the time in seconds, ctime, but how do I isolate the last two numbers and make them my "Number" variable?

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

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

Thanks, that works perfectly. I really appreciate all your help so far. :D

Problems lie now with saving and loading. I'm on to File IO and it is complex. Do I just need in the def save_student() bracket (student{}) Or will I need more than just the library? Or more specific? I'm trying to save the grade + student data. Here is the code:

max_points = [25,25,50,25,100]
assignments = ["hw ch 1","hw ch 2","quiz   ","hw ch 3","test"]
students = {"#Max":max_points}
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("Stuent 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()

Here is the tutorial task:

Now modify the grades program from section 11 so that is uses file IO to keep a record of the students.

Please can someone help me? I've given you all the info I can, and this should be the last hurdle.

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!

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!

slight issue, when I load the file, the students grades aren't preserved, just the maximum grades. This is the output from loading:

Grades 1 2 3 4 5
#Max 25 25 50 25 100

Not:

Charles 15 24 45 20 90

How do I get the students names and other data, or make sure that it saves them?

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.

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.

#Max 25 25 50 25 100
Becky 9 20 30 16 57
Charles 15 20 50 25 98
Steve 25 14 45 24 19

That's what it looks like. This is what happens:

#Max 25 25 50 25 100

It just erases the students data when pickle dumps it.

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()

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()

So this code will auto save it? Thanks. Now to the final chapter: Error checking! :P.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.