Python: Printing the return of a function

Question:

Python 2.7. The below function below returns either True or False. I’m trying to print this result. Now I know that I could just replace “return” with “print”, but I don’t want to print from within the function.

def OR_Gate():                                              
  a = raw_input("Input A:")                                        
  b = raw_input("Input B:")                                        
  if a == True or b == True:                                      
      return True                                                  
  if a == False and b == False:                                    
      return False

print OR_Gate()

When I run the below code, I’m prompted to enter values for a and b, and then the output is “None”, as opposed to either True or False. How do I just print the return of the function OR_Gate?

Asked By: Cro2015

||

Answers:

You are comparing booleans to strings True != "True" and False != "False" so your function returns None which is the default when you don’t specify a return value. You can also simplify your code using in using "True":

def OR_Gate():                                              
  a = raw_input("Input A:")                                        
  b = raw_input("Input B:")                                        
  return "True" in [a,b]
Answered By: Padraic Cunningham

Padraic has a nice answer. In addition to that, if you want to compare your raw input against a set of characters to determine truthiness, you could do something like this:

def OR_Gate():
    truevalues = ['true','t','yes','y','1']
    falsevalues = ['false','f','no','n','0']
    a = raw_input("Input A:")
    b = raw_input("Input B:")

    # if you want to have a one line return, you could do this
    # send back False if a and b are both false; otherwise send True
    # return False if a.lower() in falsevalues and b.lower() in falsevalues else True

    if a.lower() in truevalues or b.lower() in truevalues:
        return True
    if a.lower() in falsevalues or b.lower() in falsevalues:
        return False

print OR_Gate()

Some results:

$ python test.py
Input A:t
Input B:t
True

$ python test.py
Input A:f
Input B:t
True

$ python test.py
Input A:f
Input B:f
False
Answered By: zedfoxus

Well I like posting interesting answers. Here comes one:

def OR_Gate():                                              
  return eval(raw_input("Input A:")) or eval(raw_input("Input B:"))

However, using eval() through user input provides a direct access to python interpeter. So if this code is part of a website project etc, you should not use this. Other than that, I think it is cool.

Answered By: Rockybilly
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.