user2278906
user2278906

Reputation: 131

python need assistance with if function

I want this function to go test 3 statements and return the appropriate response. The three statements are and their intended responses are

'' - to have the response "blank space,
'hello' - to have the response "single word",
'world' - to have the response "another word"

The problem is 'world' is also giving the response "single word" instead of "single word again". Is there any way for python to detect hte previous response was "single word" and so it'll give the statement "single word again" if another single word is entered after the first single word?

def return_statement(statement):
    if statement == (''):
        response = "blank space"
        return response
    if ' ' not in statement
        response = "single word"
        return response
    if ' ' not in statement and response == "single word":
        response = 'single word again'
        return response

Upvotes: 0

Views: 118

Answers (2)

nqngo
nqngo

Reputation: 528

To store the state of previous response, you can add an attribute to your function. I am just adding to your function without modifying too much of your logic.

def return_statement(statement):
    // Check if has attribute, otherwise init
    if not hasattr(return_statement, "prev"):
         return_statement.prev = ''
    if statement == (''):
        response = "blank space"
        // Store answer before returning
        return_statement.prev = response
        return response
    // Fix logic
    if ' ' not in statement:
        if "single word" in return_statement.prev:
            response = "single word again"
        else:
            response = "single word"
            // Store answer
            return_statement.prev = response
        return response

Upvotes: 0

Patashu
Patashu

Reputation: 21773

In the function return_statement, response is a local variable. Meaning that after execution of the function ends and it returns, response no longer exists - we say that its scope is the function it is in. When you leave a variable's scope, it vanishes.

Here are some approaches you could take:

1) Make the caller of return_statement keep response that is returned from it around, and when it calls it also pass in response in addition to statement. This makes the caller of return_statement responsible.

2) Make response a global variable, so its scope is indefinite.

3) Make response an instance variable of a class. As long as you continue using the same class instance its value of response will therefore persist from call to call.

Upvotes: 2

Related Questions