12 Replies - 25040 Views - Last Post: 23 July 2009 - 02:15 AM Rate Topic: -----

#1 newbei  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 08-June 09

multiple choice questions in python

Post icon  Posted 08 June 2009 - 01:41 PM

Hi everbody
I am trying to make a program with multiple choice questions and unfortunalty i don't know how to write the code for it :blink: , I only now how to do input words but i don't know how to choose from a MCQ.
so please help me
thanx
Is This A Good Question/Topic? 0
  • +

Replies To: multiple choice questions in python

#2 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: multiple choice questions in python

Posted 09 June 2009 - 09:01 PM

Show us what you have and we will help you get it running...

Dream.In.Code has a policy by which we prefer to see a good faith effort on your part before providing source code for homework assignments. Please post the code you have written in an effort to resolve the problem, and our members would be happy to provide some guidance. Be sure to include a description of any errors you are encountering as well.

Post your code like this: :code:

Thanks.
Was This Post Helpful? 0
  • +
  • -

#3 Kanvus  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 42
  • View blog
  • Posts: 452
  • Joined: 19-February 09

Re: multiple choice questions in python

Posted 10 June 2009 - 09:59 PM

Do you know what a conditional statement is? *hint*
Was This Post Helpful? 0
  • +
  • -

#4 cjcamsta  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-July 09

Re: multiple choice questions in python

Posted 13 July 2009 - 09:36 PM

Hello All. I am new to python (1 week) and I hate it already!

I trying to set up a multiple choice, but with no luck. I want the end user to type in 1, 2 or 3. If not the go back to the question.
Problem is, can't find the right answer!




#start
name=raw_input( "what is you name (press enter after inputting ANY data)?")

print 'Hello there', name, 'thank you for interacting with me! My name is PC and I am your Automated-Entertainer today!'



print \
	  """I am going to ask you a few questions to find out if I can find out your integrity level.
Please answer as best as you can with either a :  '1', '2', or '3'. (remember to press enter after your entry)
"""
raw_input('\n\n\t\t\tPress enter to begin the test')
#question section
print \
	  """
Question #1
You walk into a bank and see a $100 note on the floor.

Do you:
1) Give it to the teller operator
2) Look around before picking it up and only give it back if someone sees you
3) Pick it up no matter what and run like mad before some chases you
"""

   
q1=int(raw_input('\nWhat would you do 1, 2, or 3?'))

if q1=="1": 
 print "great response"
elif q1=="2":
 print "great response"
elif q1=="3":
 print "goodo"
else:
	 print"\n I said 1, 2 or 3."
	 int(raw_input('\nWhat would you do 1, 2, or 3?'))
#*******************************************************this is where i am stuck********************************************************


print "\n\t\tHmmmm, very interesting. I need extra time to compute that!"
raw_input('\n\n\t\tPress enter to continue the test')

print \
	  '''
Well after that response I better think of something more questionable!

Question #2
If You had access to a computer at work (that was not monitored) and you saw a web site offering free downloads of
the latest movie that you haven't seen yet,

Do you:
1) Report the web site to the network administrator.
2) Download it and tell no one.
3) Download it and burn it to a DVD and then sell copies of it for $10.00 to work colleages.
'''
q2=int(raw_input('\nWhat would you do, 1, 2 or 3?'))

print "\n\t\tYou would do what?", name," I can't believe that you would do that! My information says otherwise..."

raw_input('\n\n\t\tPress enter to continue the test')

print \
	  '''
Question #3
After a delightful shopping experience at Safeway, you get home and discover that you did not pay for an item.

Do you:
1) Call the store and let them know you will pay for the item next time you are in shopping.
2) Forget about it as they make millions of dollars in profit anyway
3) Devise ways that you can use to steal more the next time you shop.
'''

q3=int(raw_input('What would you do 1, 2, or 3?'))


print "\n\t\tYep sounds like that you would do that to!"

raw_input('\n\n\t\tPress enter to continue the test')

print \
	  '''

Okay lets look at Question #4
You just filled your car up at pump 4 and it cost you $98.45 in fuel. When you go to pay the attendant says
'pump 3, that will be $13.89'.

Do you:
1) Correct the attendent
2) Pay for it ($13.89) and only correct the attendent IF you see the person from pump 3 in the line
3) Pay ($13.89) and run as fast as you can and burn black rubber all the way out of there never to return!
'''
q4=int(raw_input('What would you do?'))

print "\n\tHmmmm, very interesting. I need extra time to compute that answer also!"
raw_input('\n\tPress enter to continue')


print '\n\t Well after calculating your responses, I must say that I AM VERY SURPRISED WITH YOU!'

print "\n\tNever in my day have I ever had well, I can't finish that :(		!"
raw_input('\n\n\t\tPress enter to continue ')

total= q1 * q2 * q3 * q4 * 2
print 'I have given you a number based on your resposes ' ,name, ', your respose value is ', total



print \
	  '''
Rate your score against here

0   - 20 = Very honest! You must be an angel		 ‹(•Ώ•)›
21 - 50 = Just a few choices you may need to re think, otherwise, well done!	 *:•..•:*¨¨*:•..•:*
51 - 99 = Well at least you honest in your resposes!	.•:*¨¨*:•.
100 +   = I think your name was on Australia most wanted!

'''
raw_input("\n\nPress the enter key to exit.")



Was This Post Helpful? 0
  • +
  • -

#5 FreezingDigits  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 24
  • Joined: 17-July 09

Re: multiple choice questions in python

Posted 17 July 2009 - 11:28 AM

Hello cjcamsta, in order to get the user to input 1, 2 or 3 I would say to define a function for each question. For example

def questionOne():
	print \
	  """Question #1
You walk into a bank and see a $100 note on the floor.

Do you:
1) Give it to the teller operator
2) Look around before picking it up and only give it back if someone sees you
3) Pick it up no matter what and run like mad before some chases you
"""
	q1=input("\nWhat would you do 1,2, or 3? ")

	if q1 == 1:
		print("Great response.")
	elif q1 == 2:
		print("Great response.")
	elif q1 == 3:
		print("Goodo")
	else:
		print("\nI said 1, 2 or 3.")
		questionOne() #if the user decides to input anything that isnt 1, 2 or 3 this makes the question start
							#over again.
		
	questionTwo()#if everything goes correctly this calls the next question

def questionTwo():
	print \
	  """
	Well after that response I better think of something more questionable!

	Question #2
	If You had access to a computer at work (that was not monitored) and you saw a web site offering free downloads of
	the latest movie that you haven't seen yet,

	Do you:
	1) Report the web site to the network administrator.
	2) Download it and tell no one.
	3) Download it and burn it to a DVD and then sell copies of it for $10.00 to work colleages.
	"""
	q2=input("\nWhat would you do 1, 2 or 3?")

	print "\n\t\tYou would do what?", name," I can't believe that you would do that! My information says otherwise..."

	questionThree()#this calls the next question

def questionThree():
	#code goes in here
	#then call the next function, which would be questionFour

def questionFour():
	#code goes here
	

name = raw_input("What is your name (press enter after inputting ANY data)? ")
print('Hello there', name, 'thank you for interacting with me! My name is PC and I am your Automated-Entertainer today!')


print \
	   """I am going to ask you a few questions to find out if I can find out your integrity level.
Please answer as best as you can with either a :  '1', '2', or '3'. (remember to press enter after your entry)
"""
raw_input("\n\n\t\t\tPress enter to begin test.")
questionOne()#this begins the questions by calling the first question


	



That's what I came up with, if any doubts or errors post so that I can try to help.

This post has been edited by FreezingDigits: 17 July 2009 - 11:35 AM

Was This Post Helpful? 0
  • +
  • -

#6 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: multiple choice questions in python

Posted 20 July 2009 - 12:34 AM

@ cjcamsta

View Postcjcamsta, on 13 Jul, 2009 - 08:36 PM, said:

...

  
q1=int(raw_input('\nWhat would you do 1, 2, or 3?'))

if q1=="1": 
 print "great response"
elif q1=="2":
 print "great response"
elif q1=="3":
 print "goodo"
else:
	 print"\n I said 1, 2 or 3."
	 int(raw_input('\nWhat would you do 1, 2, or 3?'))
#*******************************************************this is where i am stuck********************************************************


'''




There are quite a few programming mistakes in this code sniplet:
1. q1=int(raw_input('\nWhat would you do 1, 2, or 3?'))
What if a user types in "haha, fooling you" instead of 1, 2 or 3?
Hint: type into the command line int("I cannot be converted to an integer!") and see what happens.
2. q1 == "1"
You converted q1 to an integer and test against a string. This will always be False.
Type 1 == "1" into your python command line and see what happens
3. Your main question:
You want to let your programm repeat the question over and over again untill a valid answer is given. The way to do this in Python is to use a while loop that is left after a valid answer is given.
choice = raw_input("choose 1, 2 or 3.")
while choice not in ["1", "2", "3"]:
	choice = raw_input("choose 1, 2 or 3.")



A side note:
you can get rid of the if statements by using a dictionary:
choice = raw_input("choose 1, 2 or 3.")
while choice not in ["1", "2", "3"]:
	choice = raw_input("choose 1, 2 or 3.")
	

reaction = {"1": "great response", "2":  "great response", "3": "goodo"}
print "Your choice was " + choice
print "This is " + reaction[choice]




@FreezingDigits

Two Problems with your Programm:
1.
	q1=input("\nWhat would you do 1,2, or 3? ")

	if q1 == 1:


Here you test an string against an integer. This will not produce an Error message but the test will silently fail, Even if q1 == "1"
2.
While your Programm will seemingly "work", there is one mayor flaw:
If a user continously makes invalid choices to say Question1 your function questionOne() calls itself over and over again. But there is a maximal depth for recursion, once reached your programm will exit with an Exception.

This post has been edited by Nallo: 20 July 2009 - 12:38 AM

Was This Post Helpful? 0
  • +
  • -

#7 FreezingDigits  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 24
  • Joined: 17-July 09

Re: multiple choice questions in python

Posted 20 July 2009 - 10:50 PM

Thanks Nallo did not know that, and would converting
q1=input("\nWhat would you do 1,2, or 3? ")



into

q1=int(input("\nWhat would you do 1,2, or 3? "))


fix my first flaw?

This post has been edited by FreezingDigits: 20 July 2009 - 10:51 PM

Was This Post Helpful? 0
  • +
  • -

#8 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: multiple choice questions in python

Posted 21 July 2009 - 02:02 AM

Hello Freezing,

that is the wrong way to fix that problem.
Now what if a user types in "haha, fooling you" instead of 1, 2 or 3? Then the int conversion will produce an error as the string "haha, fooling you" cannot be converted to an integer.
Actually always treat user input with care, they dont just type what they are supposed to do.

The correct way is to test a string against a string:
q1=input("\nWhat would you do 1,2, or 3? ")
if q1 == "1"
...


Was This Post Helpful? 0
  • +
  • -

#9 FreezingDigits  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 24
  • Joined: 17-July 09

Re: multiple choice questions in python

Posted 21 July 2009 - 12:11 PM

Thanks Nallo, right after I posted I tried the code and was wondering why I was getting an error whenever I entered a string instead of going through the if statement and recalling the function, now I understand, thanks again.
Was This Post Helpful? 0
  • +
  • -

#10 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: multiple choice questions in python

Posted 21 July 2009 - 12:47 PM

Nallo said:

The correct way is to test a string against a string:
In that case, I have a question for you Nallo. Let's say I wanted to the user to type a number from 1-1000. Following your advice, would that mean I must type in a 1000 if statements? In general, convince me that your approach scales.

Furthermore, while you are indeed correct in saying that its only meaningful to compare strings to strings, you haven't answered the original question. Which is, how to make a conversion. The user types in 1<enter> I want the number one. I don't want to just check if he typed "1". I want that number.

Would you suggest I manually do a comparison, then manually set the variable to correct integer? Like above, how is this scalable?

Conversion always has a chance of failure. The issue isn't that it can fail. The issue is how you detect and handle failure. Witness:

try:
	foo = int(raw_input("bar"))
except ValueError:
	foo = 0



What's relevant about these lines is that I have a mechanism for detecting failure. A failure to do the necessary conversion raises a ValueError. I catch this error, and then attempt to handle it. My mechanism here is to silently set a default value. Quite likely you may want to do something more complicated.

Again, you can't avoid failures. What you can do is detect and handle them instead.

This post has been edited by Oler1s: 21 July 2009 - 12:47 PM

Was This Post Helpful? 0
  • +
  • -

#11 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: multiple choice questions in python

Posted 21 July 2009 - 01:41 PM

Well Oler1s, instead of trying to convince you I will admit you convinced me. I wrote my answer with the original problem in mind, where there are only three valid input options. But as you say, my approach doesnt scale.
Was This Post Helpful? 0
  • +
  • -

#12 cjcamsta  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-July 09

Re: multiple choice questions in python

Posted 22 July 2009 - 08:00 PM

Thank you all for the responses.

ok, i fixed a lot, now I cant seem to fix it so that if the end user inputs a letter (it will come up as error) to go back to the loop.




#start

print "\t\tWelcome my friend!"
namecheck='fail'
while namecheck=="fail":
	name=raw_input( "Hello. Can I first of all have your name (press enter after inputting ANY data)?")
	if len(name)>1:
		namecheck="pass"
	else: "\nHey man, I said enter your name THEN press the enter key!.....sheeeezzzzz"
		
print '\nHello there', name, 'thank you for interacting with me! My name is PC and I am your Automated-Entertainer today!'



print \
	  """I am going to ask you a few questions to find out if I can find out your integrity level.
Please answer as best as you can with either a :  '1', '2', or '3'. (Remember to press enter after your entry)
"""
raw_input('\n\n\t\t\tPress enter to begin the test')



# if I change q1 to: q1=raw_input, then it wont accept any value, num or lett, and be in a continous loop


#question section
print "Question #1"
print name, "you walk into a bank and see a $100 note on the floor."
print \
	  """
Do you:
1) Give it to the teller operator
2) Look around before picking it up and only give it back if someone sees you
3) Pick it up no matter what and run like mad before some chases you
"""
ok='no'
while ok== 'no':
	q1=int(raw_input('\nWhat would you do 1, 2, or 3?  '))
	if q1 ==1:
		ok='yes'
		print "\nwell ok then!", name	
	elif q1 ==2:
		ok='yes'
		print "\nIf only your mother knew", name	
	elif q1==3:
		ok='yes'
		print "\nwhat the????"
		

print "\n\t\tHmmmm, very interesting,",name+ "! I need extra time to compute that!"
raw_input('\n\n\t\tPress enter to continue the test')



#question 2
print 'Well after that response,',name,'I better think of something more questionable!'

print 'Question #2'
print"\n\nIf You had access to a computer at work (that was not monitored) and you,",name,"saw a web site offering free downloads of the latest movie that you haven't seen yet,"
print name, "Do you:"
print \
'''
a
1) Report the web site to the network administrator.
2) Download it and tell no one.
3) Download it and burn it to a DVD and then sell copies of it for $10.00 to work colleages.
'''
ok='no'
while ok== 'no':
	
	q2=int (raw_input('\nWhat would you do 1, 2, or 3?  '))
	
	if q2 ==1:
		print "\nThat is quite nice of you,",name,"!"
		ok='yes'
	elif q2 ==2:
		print "\nIf only your mother knew",name+ "!!!! I can't believe that you would do that! My information says otherwise..."
		ok='yes'
	elif q2==3:
		print "\nWhat the????",name+ ", now my central processing unit is overclocking!"
		ok='yes'


raw_input('\n\n\t\tPress enter to continue the test')



#question 3
print "\nQuestion #3"
print "\n\nAfter a delightful shopping experience at Safeway,",name,"you get home and discover that you did not pay for an item."

print name,"do you:"
print \
'''
1) Call the store and let them know you will pay for the item next time you are in shopping.
2) Forget about it as they make millions of dollars in profit anyway
3) Devise ways that you can use to steal more the next time you shop.
'''


ok='no'
while ok== 'no':
	
	q3=int (raw_input('\nWhat would you do 1, 2, or 3?  '))
	
	if q3 ==1:
		print "\nThat is really going the extra mile",name
		ok='yes'
	elif q3 ==2:
		print "\nMakes me think of what you would think if you own the store,", name+"."
		ok='yes'
	elif q3==3:
		print "\nI am not going shopping with you!", name
		ok='yes'




print "\n\t\tAnd it does sound like that you," ,name+ ", would do that to!"

raw_input('\n\n\t\tPress enter to continue the test', )



#question 4
print"\nOkay lets look at Question #4", name
print"\n\nYou just filled your car up at pump 4 and it cost you $98.45 in fuel. When you go to pay the attendant says 'pump 3, that will be $13.89'."

print name, "Do you:"
print\
"""
1) Correct the attendent
2) Pay for it ($13.89) and only correct the attendent IF you see the person from pump 3 in the line
3) Pay ($13.89) and run as fast as you can and burn black rubber all the way out of there never to return!
"""

ok='no'
while ok== 'no':
	
	q4=int (raw_input('\nWhat would you do 1, 2, or 3?  '))
	
	if q4 ==1:
		print "\nwell ok then!"
		ok='yes'
	elif q4 ==2:
		print "\n",name,"I hope big brother is watching you all the time!"
		ok='yes'
	elif q4==3:
		print "\n",name,"you cheap so & so. I hope Karma gets you!"
		ok='yes'






print "\n\tThank you", name,"for choosing wisely. I see great things coming your way"
raw_input('\n\tPress enter to continue')


print '\n\tWell after calculating your responses',name,' I must say that I AM VERY SURPRISED WITH YOU!'

print "\n\tNever in my day have I ever had well, I can't finish that :(		!"
raw_input('\n\n\t\tPress enter to continue')

total= q1 + q2 + q3 + q4 + 2
if total==6:
	print name, "I believe you are an honest person! Good on you		 ‹(•Ώ•)›"

	if total ==7:
		print name, "great job!		‹(•Ώ•)›"

	elif total ==8:
		print "good job				 ‹(•Ώ•)›"
		

	elif total==9:
		print name, " not bad, you are just may need to rethink some choices   *:•..•:*¨¨*:•..•:*"

	elif total==10:
		print name, "...well you are at least honest!   *:•..•:*¨¨*:•..•:*"

	elif total ==11:
		print name, "I think you are an excon!   .•:*¨¨*:•."

	elif total >11:
		print name, "your IP address has been submitteed to the Australian Federal Police   .•:*¨¨*:•."

	else:
			print name,"thank you for trying to do this test. Maybe following instructions like inputting 1, 2 or 3 is to much for you.   *:•..•:*¨¨*:•..•:*.•:*¨¨*:•.*:•..•:*¨¨*:•..•:*"
	

print"\n\nThankyou for your time"


raw_input("\n\nPress the enter key to exit.")


Was This Post Helpful? 0
  • +
  • -

#13 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: multiple choice questions in python

Posted 23 July 2009 - 02:15 AM

hello cjcamsta,

Oler1s already gave halv the answer to your question: wrap the int conversion in a try except statement, so you can catch the ValueError that happens if a user inputs a letter:

ok='no'
while ok== 'no':
	try:
		q1=int(raw_input('\nWhat would you do 1, 2, or 3?  '))
	except ValueError:
		#Oops, bad user input
		#we must do something to go back to the top of the while loop 
		#without executing the rest of the code in the while loop
	if q1 ==1:
		...



As for going back to the top of the while loop ... It might be helpfull to read the documentation for while loops on python.org ;) . Especialaly, what the break and continue statement do inside a loop.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1