12 Replies - 2786 Views - Last Post: 07 March 2015 - 04:33 AM Rate Topic: -----

#1 albert003   User is offline

  • D.I.C Addict

Reputation: 17
  • View blog
  • Posts: 508
  • Joined: 15-December 14

New to python trying to write multiple choice quiz with a loop.

Posted 21 December 2014 - 07:42 PM

Trying to write a python program that's interactive with the user. I am currently learning python the hard way from Zed Shaw and what I like to do is after I learn a lesson, I like to make a sample program using what I learned so I can get the feel of what I learned from that lesson better. This program I am trying to write is similar to the movies 2001: A space odyssey and the 1983 war games. Trying to make it as interactive as possible. Right now, I am stuck where the user selects the game they wish to play or not play the game it won't print the response. My other question is when the user selects the "no", how would I program an endless loop that can be broken? Every time I try it won't let me. I've tried different ways and can't figure it out.
Any and all help would be greatly appreciated.

This is my program:
prompt='<'
beto1="1. Checkers"
beto2="2. Tic tac toe"            
beto3="3. surprise!!!!"
beto4="4. Global Thermonuclear War."
pc="\n* checkers\n * Tic tac toe\n * Surprise\n * Global Thermalnuclear war"
GTW="Global Thermonuclear War"
chess="chess"
stars="\nDON'T DO IT!!!!"
name=raw_input("what is your name?(press enter after inputting any data)")
print"Hello %s, my name is H.A.L." % (name)
raw_input("Shall we play a game?:")
print"What game would you like to play?"
print"%s"%(pc)
a=raw_input()
a=a.lower
if a =="global thermonuclear war":
        print"How about a nice game of chess?"
if a =="checkers":
        print"You don\'t want to play something harder?"
if a =="tic tac toe":
        print"What are you three years old?"
if a =="surprise":
        print"MY GOD, IT\'S FULL OF STARS!!!! DON'T DO IT %s!!!!"%(name)
if a =="no" or a =="n":
 a= 1
while a ==1:
  print "Too bad I was looking for a challenge, thanks for trying goodbye:"


This post has been edited by macosxnerd101: 21 December 2014 - 08:19 PM
Reason for edit:: Post your code between the code tags


Is This A Good Question/Topic? 0
  • +

Replies To: New to python trying to write multiple choice quiz with a loop.

#2 witeboy724   User is offline

  • D.I.C Head
  • member icon

Reputation: 84
  • View blog
  • Posts: 208
  • Joined: 21-June 12

Re: New to python trying to write multiple choice quiz with a loop.

Posted 22 December 2014 - 09:51 AM

View Postalbert003, on 21 December 2014 - 07:42 PM, said:

Right now, I am stuck where the user selects the game they wish to play or not play the game it won't print the response.


First, you need to add () to the end of a.lower so you call lower. Otherwise, you're just setting variable a equal to the built-in method lower.
a = a.lower()



Quote

My other question is when the user selects the "no", how would I program an endless loop that can be broken? Every time I try it won't let me. I've tried different ways and can't figure it out.


How would you like the user to be able to break the loop? Normally after saying you don't want to play a game the program would exit. If you want to enter a loop that waits for user input, put some message inside raw_input() and put that in the loop. Make sure you set a way to get outside the loop (setting a to anything but 1 in your case) Like:
if a =="no" or a =="n": a= 1
print "Too bad I was looking for a challenge, thanks for trying goodbye:"
while a == 1:
    a = raw_input('Press Enter when you're ready to play!')


However, if you're just waiting for a nonspecific response from the user, you don't need a loop for raw_input() to sit there waiting for a response. The loop would be useful if you're waiting for a specific response and you want to keep asking until that response is given. Like:
while a != 'play':
    a = raw_input('Type "play" when you are ready to play!').lower()


I would also recommend making a loop around the response to 'What game would you like to play?' in case their response isn't one of the game choices. I think it's more conventional to use numbers to choose the game rather than words, but whatever you want to do. I'll let you figure the loop part out should you decide to do that, but my hint is using if then elif then else for checking responses.
if a == 'global thermonuclear war': print 'How about a nice game of chess?'
elif a == 'checkers': print "You don't want to play something harder?"
else: print 'Please choose one of the games'


Hope that helps point you in the right direction..
Was This Post Helpful? 1
  • +
  • -

#3 albert003   User is offline

  • D.I.C Addict

Reputation: 17
  • View blog
  • Posts: 508
  • Joined: 15-December 14

Re: New to python trying to write multiple choice quiz with a loop.

Posted 23 December 2014 - 05:06 PM

I agreed that using numbers for selections made the program run smoother. I do have a few questions:
1. I know with python I can do the following with the print command:
name=raw_input("what is your name?(press enter after inputting any data)")
print"Hello %s, my name is H.A.L." % (name).
So, my question is it possible to do a similar command with raw_input? I've been experimenting and researching all over and I can't figure out how to do that same print command with raw_input. Every time I try it won't work. I want to create a loop so that if the user keys in something other than yes, ys, no, n. it will show the line you suggested. This is what I have so far. Please help me or correct me with any mistakes I've made.

if a=="yes" or a=="ys" or a=="y" or a=="sure":
    print"What game would you like to play?",pc 
else: 
    print "Please choose yes or no"
    raw_input("What game would you like to play?",pc)
#Would like to make this appear along with the else message
#so the user has to go back to the original question and
#then be asked what game they'd like to play or to get out of the program.
if a =="no" or a =="n":
    print "Too bad I was looking for a challenge, thanks for trying goodbye:"
if a =="no" or a =="n": a= 1
print "Too bad I was looking for a challenge, thanks for trying goodbye:"
while a == 1:
    a = raw_input("Press Enter when you're ready to exit the program!")

This post has been edited by andrewsw: 23 December 2014 - 06:04 PM
Reason for edit:: Added [code][/code] tags

Was This Post Helpful? 0
  • +
  • -

#4 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6561
  • View blog
  • Posts: 26,600
  • Joined: 12-December 12

Re: New to python trying to write multiple choice quiz with a loop.

Posted 23 December 2014 - 06:08 PM

@OP Please learn to use code tags, they are essential for Python code. It demonstrates how to use them directly in the area where you are typing your post.

Note that you can write this
if a=="yes" or a=="ys" or a=="y" or a=="sure":

as this
if a in ("yes", "ys", "y", "sure"):

but you should use a meaningful variable name, not a, and then don't reuse the same variable for a different purpose later on.

This post has been edited by andrewsw: 23 December 2014 - 06:25 PM

Was This Post Helpful? 1
  • +
  • -

#5 witeboy724   User is offline

  • D.I.C Head
  • member icon

Reputation: 84
  • View blog
  • Posts: 208
  • Joined: 21-June 12

Re: New to python trying to write multiple choice quiz with a loop.

Posted 23 December 2014 - 06:28 PM

[quote]

View Postalbert003, on 23 December 2014 - 05:06 PM, said:

name=raw_input("what is your name?(press enter after inputting any data)")
print"Hello %s, my name is H.A.L." % (name).

So, my question is it possible to do a similar command with raw_input? I've been experimenting and researching all over and I can't figure out how to do that same print command with raw_input. Every time I try it won't work. I want to create a loop so that if the user keys in something other than yes, ys, no, n. it will show the line you suggested.


You're right about raw_input. It waits for the user to input something. If you just want to print, just using print is correct. If you want to wait for a specific response, do what andrewsw suggested and check the responses against a list.
a = ''
while a not in ['yes','ys','no','n']"
    a = raw_input('Would you like to play a game?' 


while a == 1:
    a = raw_input("Press Enter when you're ready to exit the program!")

Also, this code ^ doesn't need a loop for anything. Leave it out of a loop, and just put in a raw_input alone so any input followed by an Enter will exit.
 raw_input("Press Enter when you're ready to exit the program!")

This post has been edited by witeboy724: 23 December 2014 - 06:30 PM

Was This Post Helpful? 1
  • +
  • -

#6 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11091
  • View blog
  • Posts: 18,973
  • Joined: 19-March 11

Re: New to python trying to write multiple choice quiz with a loop.

Posted 23 December 2014 - 07:08 PM

Just another suggestion: you can replace

if a =="global thermonuclear war":
        print"How about a nice game of chess?"
if a =="checkers":
        print"You don\'t want to play something harder?"
 #  ...




with a dictionary

response = { "global thermonuclear war": "How about a nice game of chess?", 
                  "checkers":"You don\'t want to play something harder?"  } # add any other key/val pairs
a=raw_input()
print response[a.lower]



This might look very similar, but what you're doing here is you're separating your code from your data. This will turn out to be a very good thing, and it's something you're going to want to do any time you can manage it.
Was This Post Helpful? 1
  • +
  • -

#7 albert003   User is offline

  • D.I.C Addict

Reputation: 17
  • View blog
  • Posts: 508
  • Joined: 15-December 14

Re: New to python trying to write multiple choice quiz with a loop.

Posted 24 December 2014 - 03:43 AM


I racked my brains all day and night at work trying to figure out how to work the suggestion you gave me and finally gave up after 9 hrs. I have a few new questions I'd like to ask. I have the program running pretty much the way I want, but. These are my questions:
1. This is the part I am stuck:

if b in ("surprise","3"):
while b !='H.A.L':
b = raw_input('My god, its full of stars!!!(enter programs name to enter game: ')
b = raw_input("Don\'t do it %s('Type my name to exit the program' ")%(name)
#I remember from a previous lesson from Zed Shaw's book he had a lesson that was similar to this:
print"My girlfriends name is:"
name=raw_input()
My question is earlier in the program I had the user type their name, how do I get the program to remember the name and put it in that raw_input line so it seems like the program/computer is alive and is out to get the user?
Was This Post Helpful? 0
  • +
  • -

#8 ndc85430   User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 849
  • View blog
  • Posts: 3,406
  • Joined: 13-June 14

Re: New to python trying to write multiple choice quiz with a loop.

Posted 24 December 2014 - 05:52 AM

I'm not really sure what you're asking. Are you asking how to use customise the prompt for raw_input()? If you look at the docs for that function (e.g. here for 2.7), you'll see that you can pass a string containing your prompt as an argument.

If you then want to use a variable in said string, you can put %s in the string literal and then give the variable name (I forget what this is called). An example:

str = "name"

print "What is your %s?" % str


This post has been edited by ndc85430: 24 December 2014 - 06:00 AM

Was This Post Helpful? 0
  • +
  • -

#9 albert003   User is offline

  • D.I.C Addict

Reputation: 17
  • View blog
  • Posts: 508
  • Joined: 15-December 14

Re: New to python trying to write multiple choice quiz with a loop.

Posted 24 December 2014 - 01:19 PM

Ill paste my entire program here and use the # to show what I meant. I hope its possible to do what I want and if not if you could please show me some suggestions. Thanks again for every thing and for your help.
prompt='<'
beto1="1. Checkers"
beto2="2. Tic tac toe"           
beto3="3. surprise"
beto4="4. Global Thermonuclear War."
pc="\n1. checkers\n2. Tic tac toe\n3. Surprise\n4. Global Thermalnuclear war"
GTW="Global Thermonuclear War"
chess="chess"
stars="\nDON'T DO IT!!!!"
name=raw_input("what is your name?(press enter after inputting any data)")
print"Hello %s, my name is H.A.L." % (name)
#Right here I used raw_input to have the user type in their name and when I followed it by #using print "%s"%(name) I was able to make the name automatically appear in the following #sentence. I remember in a previous lesson from Zed Shaw's book I could make the program #remember the name till the end. My question is whether or not its possible to do it using #raw_input?.
a=raw_input("Shall we play a game?:")
a=a.lower()
if a in ("yes", "ys", "y", "sure", "ok", "k"):
    print"Which game would you like to play?:%s"%(pc)
if a in ("no", "n", "no thanks"):
    while a != 'quit':
	    a = raw_input('Too bad, I wanted a challenge(type "quit" when you\'re ready to leave)	').lower()
b=raw_input("Select the game you want to play:")
b=b.lower()
if b in ("checkers","1"):
       print"Wouldn't you like to play a harder game?"
if b in ("tic tac toe","2"):
       print"Wouldn't you like to play a harder game?"
if b in ("surprise","3"):
    while b !='H.A.L':
	 b = raw_input('My god, its full of stars!!!(enter programs name to enter game:) ')
	 b = raw_input("Don't do it %s ('Type' my name to exit the program)  ")%s(name)
#right here when I use b=raw_input I wanted the program to remember the users name with out
#having to have him type it again or use print"%s"%(name). Any and all suggestions or changes are welcome. 
if b in ("global thermonuclear war","4"):
    while b !=('rosebud'):
        b = raw_input('Ah ah ah, you didn\'t say the magic word ("Type" rosebud to exit)  ')

This post has been edited by jon.kiparsky: 24 December 2014 - 01:32 PM
Reason for edit:: [code] tags

Was This Post Helpful? 0
  • +
  • -

#10 ndc85430   User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 849
  • View blog
  • Posts: 3,406
  • Joined: 13-June 14

Re: New to python trying to write multiple choice quiz with a loop.

Posted 24 December 2014 - 01:54 PM

View Postalbert003, on 24 December 2014 - 08:19 PM, said:

     b = raw_input("Don't do it %s ('Type' my name to exit the program)  ")%s(name)



Remember that what you're passing to raw_input() is a string and that string is where you'll substitute the name, so the code should be

b = raw_input("Don't do it %s" %(name))


Actually, you can omit the parentheses around name since you're only substituting one value. Also, please try to use meaningful variable names.
Was This Post Helpful? 0
  • +
  • -

#11 albert003   User is offline

  • D.I.C Addict

Reputation: 17
  • View blog
  • Posts: 508
  • Joined: 15-December 14

Re: New to python trying to write multiple choice quiz with a loop.

Posted 26 December 2014 - 07:36 PM

I see what you mean and I tried it and it worked!!!. Thank you so much for your help and to everyone else that helped me as well. I really appreciate your help answering my questions.

This post has been edited by andrewsw: 07 March 2015 - 04:36 AM
Reason for edit:: removed empty code tags

Was This Post Helpful? 0
  • +
  • -

#12 albert003   User is offline

  • D.I.C Addict

Reputation: 17
  • View blog
  • Posts: 508
  • Joined: 15-December 14

Re: New to python trying to write multiple choice quiz with a loop.

Posted 06 March 2015 - 08:44 PM

I have a new question. I've gotten along further in my lessons and I figure I could save time, energy and effort by using functions in my program.The beginning of the program I ask for the user to key in their name and I want it to continue to the function called game(): I though I could make a main function and then put within it smaller functions. Would you please help me and show me what I need to do to correct this problem? I wanted to make each section as interactive as possible and keep looping. When I wrote the original program anytime the user said no and exited the program they would leave the program I wrote but it would show the next sequence of my program.

def main():

 def HAL():
   pc="\n1. checkers\n2. Tic tac toe\n3. Surprise\n4. Global Thermalnuclear War"
   name=raw_input("what is your name?(press enter after inputting any data) ")
   print"hello, %s my name is HAL."%(name)
   a=raw_input("Shall we play a game?")
   a=a.lower()
   if a in ("yes","ys","y","ok","k","sure"):
        print"Which game would you like to play?: %s"%(pc)
   elif a in ("no","n","no thanks","nope"):
          while a !='quit':
		    a=raw_input('Too bad, I wanted a challenge (type "quit" when you\'re ready to leave)  ').lower()
         return (name)  		


 def games():
   print"Select the game you want to play:  "
   b=raw_input()
   if b in ("checkers","1"):
       print"Wouldn't you like to play a harder game?"
   elif b in ("tic tac toe","2"):
       print"Wouldn't you like to play a harder game?"
   if b in ("surprise","3"):
       b = raw_input("My god, its full of stars!!!")
       b = raw_input("Don't do it %s"%(name))
       b = raw_input("(type 'escape' when you're ready to leave)  ").lower()
   if b in ("global thermonuclear war","4"):
     while b !=('rosebud'):
       b = raw_input("Type in 'play' to begin the game:  ")
       b = raw_input("ah ah ah you didn't say the magic word...")
       b = raw_input("Type 'rosebud' to exit the program   ")

main()

This post has been edited by andrewsw: 07 March 2015 - 04:34 AM
Reason for edit:: Removed unnecessary quote and added code tags

Was This Post Helpful? 0
  • +
  • -

#13 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6561
  • View blog
  • Posts: 26,600
  • Joined: 12-December 12

Re: New to python trying to write multiple choice quiz with a loop.

Posted 07 March 2015 - 04:33 AM

Please learn to use code tags, this is particularly important with Python code.

Attached Image

You also do not need to quote a previous post, there is a REPLY button further down the page.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1