2

I appreciate all your help. My uncle helped me figure it out. I don't know if it's the best way to do it, but it worked and that's all I needed.

import time

name = raw_input("Hi, what is your name?")
print "hi, " + name + ", nice to meet you."
a1 = raw_input("Would you like to hear a knock knock joke?").lower()
if a1 == "no":
    print "OK, thanks anyways"
elif a1 == "yes":
    raw_input ("Knock Knock")
print "interrupting cow"
time.sleep(2)
print "MOOOOOO!!!!"

EDIT: Sorry I am using Windows 8 and Python 2.7.

I need help with a homework assignment. I can complete the assignment fine, but I would like know how to do it a different way. So basically I have to write a knock knock joke in python. I want to do the "interrupting cow" joke but I don't know how to get the code to interrupt while typing. Here's what I have.

name = raw_input("Hi, what is your name?")
print "hi, " + name + ", nice to meet you."
a1 = raw_input("Would you like to hear a knock knock joke?").lower()
if a1 == "no":
    print "OK, thanks anyways"
elif a1 == "yes":
    raw_input ("Knock Knock")
    raw_input ("interrupting cow")

So I have it all the way up to where I would respond 'interrupting cow who' and it would interrupt with 'MOO!!!' in the middle of me typing. I've seen something about an end' ' code but it didn't really work, or maybe I didn't use it write. Can anyone help me out?

user2825385
  • 59
  • 1
  • 6
  • 1
    You would need to replace `raw_input ("interrupting cow")` with code to display "interrupting cow", then wait for them to start typing the response (something like http://code.activestate.com/recipes/134892/), then display "moo". – Cirdec Sep 28 '13 at 01:56
  • Which OS? Unfortunately Python doesn't come with a portable `getch()` to get a single character at a time, which would really help here. – John Zwinck Sep 28 '13 at 01:58

2 Answers2

2

You could use a thread (essentially a small task) for the interruption, starting the thread running in the background immediately before asking for input.

In the example below, I define a function "punchline()", which waits for 1 second before "mooing". This function is executed in the thread started by the call to start_new_thread(). See the linked documentation for more information.

import thread
import time


def punchline():
    time.sleep(1)
    print 'MOO'

# [...]

thread.start_new_thread(punchline, ())
raw_input("interrupting cow")

For best results, randomise the sleep time.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • Excuse my lack of knowledge, but since this is my first program I would kind of like to understand it, would you mind explaining that code to me exactly? like what does thread.start_new_thread(punchline, ()) and def punchline(): do? – user2825385 Sep 28 '13 at 02:20
1

How about reading a random number (between 1 and len('interrupting cow who?')) of characters and then interrupting?

Community
  • 1
  • 1
AndrewS
  • 1,666
  • 11
  • 15