| | |
Non-programmer tutorial, stuck at list exercise
![]() |
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:
Here is the error message when I type "2" into the option selection:
What is wrong with my program and how do I fix it?
Python Syntax (Toggle Plain Text)
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)
•
•
Join Date: Aug 2005
Posts: 148
Reputation:
Solved Threads: 6
Well, you have defined function get_questions() not to take any arguments, but in lines:
and
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
):
[php]
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."
[/php]
Python Syntax (Toggle Plain Text)
while current < len(get_questions(index)):
Python Syntax (Toggle Plain Text)
print current,". ",get_questions(current)
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
):[php]
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."
[/php]
Last edited by Micko; Sep 1st, 2006 at 3:02 am.
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:
Great quiz program though, I love it! Python is a fun language to learn!
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:
Python Syntax (Toggle Plain Text)
#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."
Last edited by Ene Uran; Sep 1st, 2006 at 2:17 pm.
drink her pretty
Maybe this will help you ...
Python Syntax (Toggle Plain Text)
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
May 'the Google' be with you!
•
•
•
•
Maybe this will help you ...
Python Syntax (Toggle Plain Text)
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
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:
Here is the tutorial task:
Python Syntax (Toggle Plain Text)
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", 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_menu() menu_choice = 0 while menu_choice != 5: 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_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.
Last edited by chris99; Sep 3rd, 2006 at 8:12 am. Reason: misspelling
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:
In your case you would pickle the students dictionary!
Python Syntax (Toggle Plain Text)
# 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
Last edited by Ene Uran; Sep 4th, 2006 at 3:59 pm.
drink her pretty
![]() |
Other Threads in the Python Forum
- Previous Thread: Trying to save the info in the student library.
- Next Thread: Graphics and Game commands:
| Thread Tools | Search this Thread |
abrupt ansi anti apache approximation array assignment avogadro backend beginner binary bluetooth book builtin calculator character code converter countpasswordentry curved customdialog dan08 dictionaries dictionary dynamic examples exe file float format function gnu graphics gui heads homework ideas import inches input java launcher library line lines linux list lists loop mouse mysqlquery number numbers numeric output parsing path phonebook plugin pointer port prime programming progressbar projects py2exe pygame python random recursion redirect scrolledtext software statictext statistics string strings sum table terminal text textarea thread threading time tlapse trick tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable wordgame write wxpython xlib






