I'm having trouble with print None as a value.
Suppose here's my python code:
def a(b):
b = None
print b
def c(a):
if a:
return True
else:
return False
>>> a(1)
None # I need this "None" to show.
>>> c(a(1))
None # I don't want to print out this, but don't know how.
False
My problem is I have to "print" the None when only calling function a.
And when I pass function a to function c, I don't want the "None" to print out.
If I type "return None", Python shell will not show "None" for function a. That's why I thought I can only use "print" if I want to show the "None". But when I pass function a to function c, the "None" also gets printed out. Is there a way to only get the result secretly without printing out the "None" in the 2nd function?
I hope my question is making sense.
Thank you very much for your help.
The call c(a(1)) will execute a(1) first and then c(a(1)). Since here a(1) is not returning true, c(a(1)) will evaluate to False.
That's the reason you get following:
None
False
Try calling the function as c(a) this will return as follows:
True
This happens because a has not executed and it is having some value to it.
Hope this helps!
Related
I have a function I'm using to test in an if/then.
The issue is that I'm executing the function BOTH in the if conditional, and then again after the if statement because the function returns two items.
This just seems wasteful and I'm trying to think of ways to improve this. Here's a really basic version of what I'm trying to avoid: "True" is returned to allow the condition to pass, but then then "coolstuff()" is executed again to get more information from the function.
"coolstuff()" could possibly return false, so I can't use the returned string "stuff" as the test.
def coolstuff():
return True, "stuff"
if coolstuff()[0]:
coolthing = coolstuff()[1]
print coolthing
There's gotta be a better way to do this, no? My brain is melting a little as I try to hash it out.
I basically want to do something like this (invalid) syntax:
def coolstuff():
return True, "stuff"
if a, b == coolstuff() and a:
print b
Just collect both results into variables
a, b = fn()
if a:
# work with b
def coolstuff():
if valid:
return "stuff"
return None
data = coolstuff()
if data:
print(data)
Call the function and capture the entire returned value:
x = coolstuff()
Now you have access to both parts of the returned value, in x[0] and x[1].
Store it:
state, coolvar = coolstuff()
if state:
do_whatever(coolvar)
If in newer Python, you could use the dreaded walrus (but I prefer ti7's approach of just assigning in a separate line):
if (x := coolstuff())[0]:
print(x[1])
This is another question from https://stackoverflow.com/questions/41028828/python-does-if-not-statement-implicitly-check-2-conditions?noredirect=1#comment69265422_41028828
I am trying to further clarify the concept with ifstatement using not.
My understanding is that print secondFunction(True) will return True since randomFunction will be called but the script is returning None. Please help!
def randomFunction(value):
if value:
return True
else:
return False
def secondFunction(v):
if not randomFunction(v):
return "minus it"
print secondFunction(True)
"randomFunction" returns True to "secondFunction". At this point you have this "if" condition:
if not (True):
If it would be "True" condition was verified and "secondFunction" returns "minus it". In your example it will never enter inside the "if" condition. For this reason "secondFunction" will always return None result because it has became implicitly a procedure without a return.
I hope that was clearly to you.
I'm new to Python and I am a bit confused with the way Python treats an empty object.
Consider this code piece;
a = {}
if a:
print "a is alive!"
else:
print "a is NOT alive!"
if not a:
print "NOT a!"
else:
print "a!"
if a is None:
print "a is None!"
else:
print "a is NOT None!"
I get the following output for this code piece.
a is NOT alive!
NOT a!
a is NOT None!
Edit::
I am under the assumption that an object initialized by {} is a Valid Object. Why doesn't Python treat it that way? and why do I get diff output for diff If conditions?
Edit 2::
In C++, when I say
Object obj;
if (obj){
}
It will enter the IF block if obj is NOT NULL(regardless if it is garbage value or whatever)
But the same thing when I translate to python.
a = {} #This is a valid object
if a:
# Doesn't work!
Why? and I read Python evaluates {} as False. Why is that?
Empy dict/sets/lists etc are evaluated as false. None is its own type, with only one possible value.
https://docs.python.org/2.4/lib/truth.html Tells you what is evaluated as true and false
I see nothing weird in your output.
Let's go step-by-step:
a is dictionary, more specifically a dictionary object;
a is a dictionary, but it's empty, so its truth value is False
Therefore:
The first if, since a is False, prints the else statement and that's right;
The second if, since not a evaluates to True because a is False, prints the if part and that's right too.
Last, but not least a is not a None object, but a dict object, so it's right too that the else part is taken and printed.
It is a valid python object, but it is empty, so it is treated as a False, the same goes for lists [] or numbers 0. You do have a dict, but it is not a None object.
with
a = {}
you are creating an dictionary object which is not NoneType you can
check the class of your object with
type(a)
which will give you:
type dict
if not a:
will return False if a has already any members and True if a is just and empty list
I just started learning Python and I've just been messing around typing different codes for practice to learn, and I made this code:
import math
def lol():
print (math.cos(math.pi))
print ("I hope this works")
def print_twice(bruce):
print bruce
print bruce
print_twice(lol())
When I run it, my output is:
-1.0
I hope this works
None
None
How come it isn't printing the function lol() twice?
Your code print_twice(lol()) is saying to execute lol() and pass it's return value into print_twice(). Since you didn't specify a return value for lol(), it returns None. So, lol() is printed once when it gets executed, and both print statements in print_twice() print passed value of None.
This is what you want:
def lol():
print (math.cos(math.pi))
print ("I hope this works")
def print_twice(bruce):
bruce()
bruce()
print_twice(lol)
Instead of passing the return value of lol(), we are now passing the function lol, which we then execute twice in print_twice().
You should note that printing is different from returning.
When you call print_twice(lol()) it will first call lol() which will print -1.0 and I hope this works and will return None, then it will continue calling print_twice(None) which will call print None twice.
How you might run as expected:
def lol():
print "lol"
def run_twice(func):
func()
func()
run_twice(lol)
def a(b=[]):
b.append(1)
return b
print a()
print a()
All of a sudden i got a list with 2 elems, but how? Shouldn't b be getting set to empty list every time.
Thanks for the help
Default arguments are only evaluated once, when the function is defined. It retains the same object from one invocation to the next, which means that the same list keeps getting appended to. Use a default value of None and check for that instead if you want to get around this.
Nothing to do with closures, at least not in the usual sense.
The default value for b is not "a new empty list"; it is "this particular object which I just created right now while defining the function, initializing it to be an empty list". Every time the function is called without an argument, the same object is used.
The corrected version, for the reasons given in other answers, is:
def a(b=None):
b = [] if b is None else b
b.append(1)
return b
default arguments are evaluated (once) when the function is defined, not each time it is called.
try this:
def a(b=None):
if b is None
b = []
b.append(1)
return b
print a()
print a()