1

This may be impossible, but (without making a variable be set after the computer prints something) know if the computer has printed something last, or the user. e.g.

answer = raw_input("Say something.")
if "ok" in answer.lower():
    print "Yay!"
if "poo" in answer.lower():
    print "That's very childish"
if (computer hasn't printed anything already):
    print "I'm not very talkative."

I have a lot of if branches to process the users input, but so loads of elifs and an else won't work. Thanks

jamylak
  • 128,818
  • 30
  • 231
  • 230
Ben Hack
  • 91
  • 10

2 Answers2

0

As you already mentioned, you could just set a variable, but that doesn't look nice.

Alternatively you could collect your output:

answer = raw_input("Say something.")
output = []
if "ok" in answer.lower():
    output.append("Yay!")
if "poo" in answer.lower():
    output.append("That's very childish")
if not output:
    output.append("I'm not very talkative.")
for o in output:
  print o

Disclaimer: I don't do much Python coding, so I have no idea if that's pythonic enough.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • I have already made all the print statements... This would take just as long, though is a interesting idea – Ben Hack May 27 '13 at 16:17
  • Nothing that a little search-and-replace (with the regex-supporting editor of your choice) can't fix: `s/print \(.*\)/output.append(\1)/` ;-) – Joachim Sauer May 27 '13 at 16:20
  • Yes though I still have to insert the )s afterwards and I have lots of prints all around the place. – Ben Hack May 28 '13 at 17:54
0

You also define a inner function to handle the printing and setting of the variable:

def handler(answer):
  handler.responded = False
  def respond(output):
    handler.responded = True
    print output
  if "ok" in answer:
    respond("Yay!")
  if not handler.responded:
    respond("I'm not very talkative")

This uses the "nonlocal"-replacement as discussed in this question.

If you could use Python 3, this code could be a bit nicer by using nonlocal:

def handler(answer):
  responded = False
  def respond(output):
    nonlocal responded
    responded = True
    print(output)
  if "ok" in answer:
    respond("Yay!")
  if not responded:
    respond("I'm not very talkative")
Community
  • 1
  • 1
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • This would include writing all my code into a function, and replacing all the prints with responds. Another good idea, but I'm looking for if there's a value already stored in python to tell me really. – Ben Hack May 27 '13 at 19:06