0

I am trying to basically pass over the rest of an if statement once a function is run to determine a certain value to be 0 or 1. If the value is 0, It passes the rest of the if statement, if it's 1, it continues with the if statement it's in and run accordingly. Here's the code:

test2.py

import os, sys
from functiontest import function

message = 'foo'
check = 0

if 'foo' in message:
    check = function(message,check)
    print(check)
    print('bar')

if check == 0:
    print('foo not recognized')

with the function file being

functiontest.py

import os, sys

def function(a,b):
    print('checking message')
    a = a.split()
    print(a)
    if a[0] == 'foo':
        b = 1
        print(b)
        return b
    else:
        b = 0
        return b

When a word other than "foo" exactly as written is detected, it should only output "foo not recognized". With a word like "foot", it still runs the code within the if statement because it contains foo, which I don't want it to. Is there a way to pass over the rest of the if statement from the function side? I know how to do it with an if else statement in the main test2.py code because I pass back the check argument, but I'm looking to make the main code as clean as possible, so is there a way to accomplish that within functiontest.py? Thanks.

1 Answers1

0

This could be solved by doing what is suggested in: How to exit an if clause

Not clear to me is this will solve your issue but this would be my code:

import os, sys

def check_message(message):
    print('Checking message')
    for m in message.split():
        if m == 'foo':
            return True
        else:
            return False


def wrapper(message):
    if 'foo' in message:
        check = check_message(message)
        if check:
            return
        print(check)
        print('bar')


message = 'foo'
wrapper(message)

but I don't understand why the double check on the message and not just:


def wrapper(message):
    if check_message(message)
        return
    print('bar')


message = 'foo'
wrapper(message)

In this case, 'bar' will be printed only if the message does not container 'foo' words.

Also, regarding your code, you don't need to give check as an input, since you are not using it in the function function, you overwrite it in any case.

It's also better to use True and False instead of 1 and 0

dzang
  • 2,160
  • 2
  • 12
  • 21
  • That works, much appreciated! Reason I do a double check on it is because I plan to use it to allow inputs after 'foo', so like example the message could be 'foo 5' and I would split it into a list and use that 5 for something :) – Redicebergz Mar 14 '19 at 14:41