hi guys i am a beginner to python. Just now completed a few sets of lessons and i'm trying out the exercises given at the end of each chapter. I have learned till the stage of basics in defining a function. But still i am confused.

##This program runs a test of knowledge

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"]]

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

How can i expand this program so that the program has a menu with options to take up the test, viewing the questions and answer and option to quit? Also i need to add a new question to the list for eg., "What noise does a truly advanced machine make?", with the answer of "ping". Thank you.

Recommended Answers

All 17 Replies

For a menu, just make a new function. Have it print out the choices on screen, including a number, and then the option is chosen by inputing a number. You could use the raw_input() function, but this is rather crude, as it throws errors, if it recieves a value that it does not have a statement for.

I suppose you could use an 'else' statement, which then starts the menu again. Try it and come back to me if you need more help.

a menu could look something like this:

import sys
while 1:
  print """
1)Take Test
2)Test History
3)Exit"""
  choice = raw_input("Option: ")
  if choice == "1" or choice == "Take Test":
    print "choice 1 was made..."
    #Call the take test function
    #here.....
  elif choice == "2" or choice == "Test History":
    print "choice 2 was made"
    #some other function.....
  elif choice == "3" or choice == "Exit":
    print "exiting..."
    sys.exit()
  else: print "Not a valid entry..."

as for a new question, look at how the given questions already are. To add a new one fallow the same format. E.G. list inside of a list.

Thanks for your replies. I came up with this code, but i get syntax error "unindent does not match any outer indentation level".

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"]]

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
	elif answer != given_answer:
		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 up the test"
	print "2. Show me the questions with answers"
	print "3. Show me my score"
	print "9. Quit"

	menu_item = input("Select your option from the menu:")
	if menu_item == 1:
		run_test(get_questions())

    elif menu_item == 2:
        get_questions()
    
    elif menu_item == 3:
        run_test(questions)
		
        
print "Thank you"

Oh my God!
You are using a wild mix of tabs and spaces for your code indentations! That is an absolute nono.

Avoid tabs, since sooner or later you will mix them with spaces. Most Pythonians use 4 spaces for indenting a code block. Stick with that!

Thank you vegaseat. i'll use spaces and get back here.

I always use the tab key. It just looks neater to me...

I always use the tab key. It just looks neater to me...

Many editors use different tab settings, so your code can look rather messy to someone else. Just take a look at slmsatish's tabbed code on the post before. Also, if you want to convert your code to Python3 syntax with the 2to3 .py utility program, forget it! That one hates tabs, rightfully!

Most editors written for programming in Python will do the proper indentations for you, but may not translate tabs correctly. I generally refuse to even check out code that uses tabs. Looks like junk on my editor.

Python is an indentation based syntax, why screw it up with inconsistent tabs.

Thanks for your reply SgtMe. May be i should try out those when i'm well versed in this like you people. Now i replaced all the tabs with spaces. I used Notepad++ to type the program. Now i dont get indentation error. Thanks vegaseat. But i'm doing some mistake in calling the functions in the loop. Don't know where i'm going wrong. Here is the new one.

true = 1
false = 0

def get_questions():
    return[["What color is the day time sky on a clear day?","blue"],\
    ["What is the answer to life, the universe and everything?","42"],\
    ["What is the three letter word for mouse trap?","cat"],\
    ["What noise does a truly advanced machine make?","ping"]]

def check_questions(question_and_answer):
    question = question_and_answer[0]
    answer = question_and_answer[1]
    if answer == given_answer:
        print "Correct"
        return true
    else:
        print "Incorrect, the correct answer is:",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_questions(questions[index]):
            right = right+1
        index = index+1
    print "You got ",right*100/len(questions),"% right out of", len(questions)

def print_options():
    print "------------------------"
    print "1. Take up the test"
    print "2. Show me the questions and answers"
    print "3. Show me my score"
    print "4. Show me the options"
    print "9. Quit"
	
menu_item = 0
while menu_item != 9:
    menu_item = input("Select your option from the menu:")

    if menu_item == 1:
        run_test(get_questions())

    elif menu_item == 2:
        get_questions()

    elif menu_item == 3:
        run_test(questions)

    elif menu_item == 4:
        print_options()

print "Good Bye"

I got it working, study the changes I made.
I took the score option out because it shows you your score when the test is done. If you really want it to keep score, you'll need to figure out a way to append your score to a list outside of the function def.
Maybe return the score?
But anyway, that's as much as I can help.

true = 1
false = 0

def get_questions():
    return[["\nWhat color is the day time sky on a clear day?","blue"],\
    ["\nWhat is the answer to life, the universe and everything?","42"],\
    ["\nWhat is the three letter word for mouse trap?","cat"],\
    ["\nWhat noise does a truly advanced machine make?","ping"]]

def check_questions(q,a):

    questions = get_questions()    

    if questions[q][1] == a:
        print "Correct\n\n"
        return true
    else:
        print "Incorrect, the correct answer is:", questions[q][1]
        return false

def run_test(questions):
    if len(questions) == 0:
        print "No questions were given."
        return
    index = 0
    right = 0
    while index<len(questions):
        QnA = get_questions()
        print QnA[index][0]
        answer = raw_input("whats the answer? ")
        if check_questions(index,answer) == True:
            right = right+1
        index = index+1

    print "You got ",right*100/len(questions),"% right out of", len(questions)

def print_options():
    print "\n------------------------"
    print "1. Take up the test"
    print "2. Show me the questions and answers"
    print "3. Show me the options"
    print "9. Quit"
	
menu_item = 0
while menu_item != 9:

    print_options()

    menu_item = input("\nSelect your option from the menu:")

    if menu_item == 1:
        run_test(get_questions())

    elif menu_item == 2:
        ques = get_questions()
        print ques

    elif menu_item == 3:
        print_options()



print "Good Bye"

Thanks a lot Tech B. Got through it. But have to find a way to return the score out of the loop. Thanks to everyone in this forum who helped me solve this.

Could you mark the thread solved please.
And your welcome for the help. I try to help when ever I can.

sorry vegaseat, but I use Notepad, NOT NOTEPAD++

Ich bin der MS-Noob

Same here, I learned on a good old plain notepad. I some times download source code that's all mushed together and use the IDLE that came with python.

I don't like IDLE. I was using netbeans but it got annoying, cos even if I wanted to test something small before I put it in a program, I had to make a new project. The only advantages of netbeans is that it shows typing errors as you go, and freezes any errors that come up so you don't have to print screen and paste in paint!

Just a note:
NotePad is for writing little notes. Yes, you can use a screwdriver as a hammer, but you really should use the right tools for the job. If your job is writing Python programs use IDLE, SPE, DrPython, PyScripter, Editra, or one of the many other Python specific offerings.

I disagree. Though there are advantages to using full IDEs such as netbeans, Notepad's simplicity still does it for me. It's free from clutter, and you don't have to fiddle around with settings and installation and whatever. It's there, it works, it's done. Just like using a belt sander to sand down a 1cm by 1cm piece of wood...

Though there are advantages to using full IDEs such as netbeans

Vega is not talking about big editors like netbean that support many languages.
Pyscripter,SPE are small python editors that work out the box,just paste in code an run it.
And will give a god error message and where in code if somthing goes wrong.

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.