heya guys - new to posting here, but i have browsed the forums for help over this year so far. obvisoulsy im also new to python, only trying it since march.

Im trying to write some code for a 'knock knock' program. It uses a txt file for the jokes, prompts the user at the appropriate points. All this is working fine - however I'm supposed to randomise the jokes.
Im guessing I should be using random shuffle for this. I just cant get it to work. Should I be setting the shuffle up in it's own def, or can it be part of main?? I had a bit of a play with this and no success.

Anyway - heres the working code so far - any hints as to where my shuffle needs to appear would be great ~ :)

def main():
    k = open("knockknock.txt", "r")
    line = k.readline()
    while len(line)!=0:
        joke = line.split(',')
        comeback = joke[0]
        punchline = joke[1]

        print "\nKnock Knock\n"
        if raw_input("""\nEnter choice:
        0 : Who's there?
        1 : Go away!\n""")=="0":
            print comeback
        else:
            print "\nOK, cya!"
            break
      
        print """\nEnter choice:
        0 :""",comeback,"""who?
        1 : Go away!\n"""
        if raw_input()=="0":
            print punchline
        else:
            print "\nOK, cya!"
            break
        
        print "bwahahahahaha\n\n"


        if raw_input("Can you handle another (Y/N)? ").upper() == "N":
            print "\nOK, cya!"
            break
        else:
            line = k.readline()
main()


raw_input("\n\npress ENTER to continue")

Recommended Answers

All 5 Replies

My Phyton knowledge is nill, but I after looking at your code, it doesn't seem too difficult. I don't know the syntax, but I believe you should load the jokes into an array and than get a random array.

Random:
http://effbot.org/pyfaq/how-do-i-generate-random-numbers-in-python.htm

From what I can understand the syntax would be something like this

a=[]
a.append(new line for each joke)

and then you just get a random number and say a[random number].

This shows you were to place random.shuffle() ...

""" knockknock.txt for testing:
    
comback1,punchline1
comback2,punchline2
comback3,punchline3
comback4,punchline4

"""

import random

def main():
    k = open("knockknock.txt", "r")
    line_list = k.readlines()

    print line_list  # for testing only
    random.shuffle(line_list)
    print line_list  # for testing only

    n = 0
    while len(line_list)!=0:

        line = line_list[n]
        # increment n
        n += 1

        joke = line.split(',')
        comeback = joke[0]
        punchline = joke[1]

        print "\nKnock Knock\n"
        if raw_input("""\nEnter choice:
        0 : Who's there?
        1 : Go away!\n""")=="0":
            print comeback
        else:
            print "\nOK, cya!"
            break
      
        print """\nEnter choice:
        0 :""",comeback,"""who?
        1 : Go away!\n"""
        if raw_input()=="0":
            print punchline
        else:
            print "\nOK, cya!"
            break
        
        print "bwahahahahaha\n\n"


        if raw_input("Can you handle another (Y/N)? ").upper() == "N":
            print "\nOK, cya!"
            break

main()


raw_input("\n\npress ENTER to continue")

Now you can work in simplifying your code.

You can simplifying your code as suggest på vegaseat.

Think about design,now you have one long main function.
This make code hard to read and if you want to add more code this will soon get difficult.

Split code upp in more function.
A shorter function is eaiser to test and read.
A function keep code local,so you can use in and other code if you need that later.

Just some code to show you what i mean.

import random

def read_in_file():
    shuffle_txt = open("kn.txt", "r").readlines()
    random.shuffle(shuffle_txt)
    return shuffle_txt

def do_domething(arg):
    '''This is a dok string you can explain what this function do'''
    my_list = arg  
    print my_list  #Just a test print to show how you can get data in from read_in_file()
    
def main():
    while True:
        print '(1)play Knock game'
        print '(2) Quit'
        choice = raw_input('Enter your choice: ') 
        if choice == '1':
            shuffle_txt = read_in_file()
            do_domething(shuffle_txt)           
        elif choice == '2':            
           return       
        else:
            print 'Not a correct choice:', choice        
        
if __name__ == "__main__":
    main()

heya again - thanks to all here

finito - i knew I needed to count/random lines - or shuffle the lines - but i couldnt get the code to read the lines as numbers .... solved below I think

vegaseat - ill try putting that in later today - just got home & wanted to check replies here - I had put the shuffle function in up after my line variable before, but got an error, but thats without the extra breakdown into actual line number - ill pop that in, tidy it all up & will check back a bit later with result of this

& snippsat - my lecturer already tells me i already have a terrible habit of over complicating every bit of code I write - and I can see I do :/ - breaking down the code into relevent definitions does makes sence to me - especially for the benefit of someone else coming along and working with it.

But as i said - only 3 months of python under my belt ... it does all make pretty good sence to me, especially when reading the theory of functions & variables and stitching it all together .... its just so pedantic!!!!

ok - all working as:

import random
def main():
    k = open("knockknock.txt", "r")
    line = k.readlines()
    random.shuffle(line)
    n = 0
    while len(line)!=0:
        line_number = line[n]
        n += 1
        joke = line_number.split(',')
        comeback = joke[0]
        punchline = joke[1]

        print "\nKnock Knock\n"
        if raw_input("""\nEnter choice:
        0 : Who's there?
        1 : Go away!\n""")=="0":

            print comeback
        else:
            print "\nOK, cya!"
            break
      
        print """\nEnter choice:
        0 :""",comeback,"""who?
        1 : Go away!\n"""
        if raw_input()=="0":

            print punchline
        else:
            print "\nOK, cya!"
            break
        
        print "bwahahahahaha\n\n"

        if raw_input("Can you handle another (Y/N)? ").upper() == "N":
            print "\nOK, cya!"
            break
main()
raw_input("\n\npress ENTER to continue")

a couple of questions tho, if i can ....

snippsat - i understand everything looks neater & easier for other coders to read if things are packaged up into their own defs ... but in this particular example, ive set the game up to give the appropriate choices at each level - sure, they are both continue or quit choices, but both the continue choices are slightly different. I'd need two seperate defs wouldnt i, to do this??
Is there any limit at all to how many defs you set up??
and if __name__ == "__main__": ... this is setting up a loop thru the main defenition?? I havent seen it like this before. Before asking for help I had a line = k.readlines() to loop up thru the jokes again, which worked fine while i was running thru them in order - but once the shuffle command was put in, it didnt work. - taken out, of course it does now work, as displayed above.

vegaseat - i think the biggest prob i had shuffle wise was figuring out how to count my lines properly - which is now sorted - this will help in a few other problems i have to answer too
*hopefully*

thanks again guys :)

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.