if var == False - python

In python you can write an if statement as follows
var = True
if var:
print 'I\'m here'
is there any way to do the opposite without the ==, eg
var = False
if !var:
print 'learnt stuff'

Use not
var = False
if not var:
print 'learnt stuff'

Since Python evaluates also the data type NoneType as False during the check, a more precise answer is:
var = False
if var is False:
print('learnt stuff')
This prevents potentially unwanted behaviour such as:
var = [] # or None
if not var:
print('learnt stuff') # is printed what may or may not be wanted
But if you want to check all cases where var will be evaluated to False, then doing it by using logical not keyword is the right thing to do.

Python uses not instead of ! for negation.
Try
if not var:
print "learnt stuff"
instead

var = False
if not var: print 'learnt stuff'

I think what you are looking for is the 'not' operator?
if not var
Reference page:
http://www.tutorialspoint.com/python/logical_operators_example.htm

Related

Executing a function only if a variable is true in python?

for instance say i wanted to print "var is true" only if a variable named myVar = True how would this be possible I've tried a if myVar = True and other methods but none of them seem to work
one = sign is assigning a value, while == is for comparison. so: if myVar == True: is the right way to check that.
Also, in Python you can simply use if myVar: to the same effect.
You might want to use something like this:
if myVar == True:
print("var is true")
You use == to check equality in Python (not to be mistaken with =).
You can also ditch the True and use:
if myVar:
print("var is true")
In Python you can do it in 3 different ways:
if myVar == True:
# code here
if myVar is True:
# code here
if myVar:
# code here

Python equivalent of omitting second part of ternary operator (a if a else b)

In some languages (I think php and Java) you can omit the second part of the ternary operator as such:
a = "This is a string"
result = a ? : False
The above should be equivalent to
a = "This is a string"
result = a ? a : False
I want to shorten the ternary operator in the following (simplified) python code:
def myFunc():
return "This string could be empty, but now it's not."
result = myFunc() if myFunc() else False
print(result)
This will print the string if it's not empty, but print False when it is empty.
The reason why I want it shorter is because now, I have to call myFunc() two times instead of just once if you were able to omit one of them as is possible in other languages.
Of course I could just assign myFunc() to a variable and use the variable twice in the ternary operator but this would make it bigger again.
Is there any easy way to do this in python? Or is this just not possible?
You can use or here as an empty string evaluates as a Falsey value:
result = myFunc() or False
Refer to Truth Value Testing

Function that checks if a string occurs in another string

I'm currently reading and doing each and every of the exercises in John Guttag's Introduction to Computation and Programming Using Python. One particular problem I cannot solve for the life of me:
Write a function isIn that accepts two strings as arguments and
returns True if either string occurs anywhere in the other, and False
otherwise. Hint: you might want to use the built-in str operation in.
I went through every discussion I could find here, tried with both in and find, constantly changing something in the code, but every time I would run my program to check if 'abc' occurs in 'efg' the answer would be True.
Any idea how to solve it? Again, I need to write a function, not simply go with in like:
x='abc'
y='efg'
if x in y:
# Blah
else:
# another Blah
The code I wrote (I'm adding this as apparently some would like to see it) was basically this:
def isIn(x,y):
if x in y or y in x:
return True
else:
return False
a='abc'
b='efg'
isIn(a,b)
if True:
print "True"
else:
print "False"
The problem is that you are completely ignoring the return value of the function isIn, and the reason why you always get True printed by the code is that the condition you are checking in the if statement is the boolean constant True, which is of course always True.
Try changing your code to:
a='abc'
b='efg'
r = isIn(a,b)
if r:
print "True"
else:
print "False"
Simply put:
x=input('Enter string #1: ')
y=input('Enter string #2: ')
#can also just define x and y separately in the console and invoke the
# function on those values
def isIn(x,y):
if x in y:
return True
elif y in x:
return True
else:
return 'False'
print(isIn(x,y)) #invokes and prints the results of the function evaluating
#the x and y the user inputs; otherwise nothing is returned
I'm getting the impression that you are a newcomer to Python, so here is the solution to your problem below laid out just as the question asks :)
def isIn(string_1, string_2): #This is the function that returns true/false
if (string_1 in string_2) or (string_2 in string_1):
is_in = True
else:
is_in = False
return is_in
if __name__ == "__main__":
string_1 = input ("String 1 here: ")
string_2 = input ("string 2 here: ")
is_in = isIn(string_1, string_2) #Calls function with strings as parameters
print (is_in) #Prints the evaluation of the function after it has run
The problem with your code was that you say if True, but you aren't giving it anything to check against. if True on its own is always true.
If you want me to explain how this code works in more detail I'd be happy to do so :)
you are not printing the isIn(x,y)
def is_in(x,y):
if x in y or y in x:
return True
else:
return False
print(is_in("hello","hello world"))
try this :)

Python ternary_operator (do-somthing if flag else do-another)

Is there method by using python if/else (ternary_operator) to achieve this function:
flag = True # or False
if flag:
print 'abc'
else:
pass
I tried to using:
print 'abc' if flag else ''
But a blank line will be print if the flag == False. Because:
print 'abc' if flag else '' == print ('abc' if flag else '')
Is there any way can make print nothing if flag == False without using ;?
Thanks in advance.
By the way, I'v tried using lambda, but it wasn't successful, here my code:
a = lambda x: x if False else None
print a(1)
Result:
>> python a.py
None
In Python 2.X print is a statement while in 3.X print is a function.
You can do from __future__ import print_function and print will now be a function. You can then do print("abc") if condition else None if you want to print in an expression. Note that the value of the expression is always None, but it may or may not print "abc" depending on the value of condition.
You may want to reconsider your programming style. It can be confusing with side-effects, like printing, happening in expressions. Furthermore, Python isn't ideal for functional programming, in my opinion, for a number of reasons. For example:
There are no proper tail calls so you would easily get stack overflows (or max recursion depth errors).
You cannot have statements in lambda-expressions. This includes yield statements that otherwise could be used to mitigate the lack of tail calls.
Why not just:
if flag:
print "abc"
else:
# do something else
?
from __future__ import print_function
print('abc') if flag else None

How can this behavior be acomplished? Python "short circuting" test

I have the following code:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
else:
pass
return False
What i need to know the following: in case the if condition evaluates to true, will the function stop looking in the list and never return False? Or do i need a break statement?
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
break
else:
pass
return False
If the following code does not solve my problem, what can i use to do simulate that behavior?
Thanks
return is the end of the line, and nothing else will happen in that function afterwards. On the other hand, you could rewrite your function as
def testGeodatabase(self):
return self.outputGeodatabase in self.gp.ListWorkspaces("*","ALL")
You don't need the break keyword in the code above. Actually, you don't need the
else:
pass
either. The
return True
will exit the function.
The return statement will indeed cause the function to be exited at that point. No further code is executed in the function.
Here is a simple test which you could run to prove the point:
def someFunction(nums):
for i in nums:
if i == 1:
return "Found 1!"
return "Never found 1"
And running it:
>>> someFunction([2])
'Never found 1'
>>> someFunction([2,1,3])
'Found 1!'
I think that using any() is the best choice:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
return any(x == self.outputGeodatabase for x in geodatabaseList)

Categories

Resources