Gumpy
Gumpy

Reputation: 39

Python asking game

I'm making a question game(along the lines of 20 questions) but I want my program to only ask a question once. I have tried using enumerate to give each string in ques a value then had an if statement saying if i = i: i != 1 hoping that that would change the value of i to something else so that it doesn't repeat the questions but that didn't work. Any help would be nice this is my first time programming a question game and have high hopes for it as soon as I can get it to a stable point.

import sys, random
keepGoing = True
ques = ['What does it eat?', 
        'How big is it?', 
        'What color is it?', 
        'How many letters are in it?',
        'Does it have scales?',
        'Does it swim?',
        'How many legs does it have?'
        ]

ask = raw_input("Want to play a game?")
while keepGoing:
    if ask == "yes":
        nextQ = raw_input(random.choice(ques))
    else:
        keepGoing = False

Upvotes: 0

Views: 808

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56634

I suggest using random.sample on your question list; it will get the desired number of random questions with no repeats.

Here is some cleaned-up code:

# assumes Python 2.x
from random import sample
from time import sleep

NUM_QUESTIONS = 4

questions = [
    'What does it eat?', 
    'How big is it?', 
    'What color is it?', 
    'How many letters are in it?',
    'Does it have scales?',
    'Does it swim?',
    'How many legs does it have?'
    # etc
]

def get_yn(prompt):
    while True:
        val = raw_input(prompt).strip().lower()
        if val in {'y', 'yes'}:
            return True
        elif val in {'n', 'no'}:
            return False

def play():
    for q in random.sample(questions, NUM_QUESTIONS):
        print(q)
        sleep(2.)

def main():
    while True:
        play()
        if not get_yn("Play again? "):
            break

if __name__=="__main__":
    main()

Upvotes: 2

Luis Masuelli
Luis Masuelli

Reputation: 12333

Do something like this:

for question in random.shuffle(ques):
    #your code here, for each question

BTW if your code is as-is, as you wrote it, it generates an endless loop. Try to reformule it.

Upvotes: 3

Related Questions