Executing a function only if a variable is true in python? - 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

Related

Determining if both variables are True or False

I'm trying to make a function where two variables are in one if statement. followed by a(n) == True. It doesn't work, but here's what I tried in a better format.
if var1, var2 == True:
print("This function is correct")
else:
print("This function doesn't work")
but it returned this message:
Invalid Syntax
Is there a way to make this function possible?
Keep in mind that you can take advantage var1 and var2 are booleans, so:
if var1 and var2:
# your logic
Alternative, you can use the all function
if all([var1, var2]):
# your logic
Note: you don't need to check equality for True in a conditional, the point is to take advantage of that.
For determine if both statements are true you can use "and" logical operator.
https://www.w3schools.com/python/python_operators.asp
if var1 and var2:
print("This function is correct")
else:
print("This function doesn't work")
And, if you need to look whether it is true, you don't need to add == True.
For a more general solution to testing if multiple variables are all True, you can use the all function instead of performing multiple and operations:
if all((var1, var2, var3, var4)):
print("This function is correct")
If you are trying to find whether both of the variables are true or false in python you can simply type 'and' between the two arguments(variables) in your if conditions.
I suggest using all().
#Note: all takes only one argument, therefor we have to add var1 and var2 to a iterable.
var1,var2 = True,True
if all((var1, var2)):
print('all true')
output
all true
Another option would be to use .count().
var1,var2 = True,True
trues = [var1,var2]
if trues.count(trues[0]) == len(trues):
print('all true')

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 :)

How do I get a python program to do nothing?

How do I get a Python program to do nothing with if statement?
if (num2 == num5):
#No changes are made
You could use a pass statement:
if condition:
pass
Python 2.x documentation
Python 3.x documentation
However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.
If you have something like this:
if condition: # condition in your case being `num2 == num5`
pass
else:
do_something()
You can in general change it to this:
if not condition:
do_something()
But in this specific case you could (and should) do this:
if num2 != num5: # != is the not-equal-to operator
do_something()
The pass command is what you are looking for. Use pass for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.
For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:
if num2 != num5:
make_some_changes()
This will be the same as this:
if num2 == num5:
pass
else:
make_some_changes()
That way you won't even have to use pass and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.
You can read more about the pass statement in the documentation:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
if condition:
pass
try:
make_some_changes()
except Exception:
pass # do nothing
class Foo():
pass # an empty class definition
def bar():
pass # an empty function definition
you can use pass inside if statement.
if (num2 == num5):
for i in []: #do nothing
do = None
else:
do = True
or my personal favorite
if (num2 == num5):
while False: #do nothing
do = None
else:
do = True
You can use continue
if condition:
continue
else:
#do something

if var == False

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

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