Determining if both variables are True or False - python

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

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

How to create a list of conditions?

I am trying to create an if else code where there is about 20conditions for the elif, how do I create a list of conditions where i can just type something such as:
uno= <9
lol= >20
crad= =<3
list={uno,lol,crad}
if 13=list:
print("yay")
elif 13!=list:
print("nay")
That's my current code
It should print "yay", instead there is syntax error
It's not actually simpler than writing a chain of if/elif/elif etc, but something like this seems to do what you are asking:
predicates = [lambda x: x<9, lambda x: x>20, lambda x: x<=3]
if all(y(13) for y in predicates):
print("yay")
else:
print("nay")
Each predicate is a small anonymous function (a lambda) which receives a single argument and evaluates to either True or False. If you have a large number of arguments you want to check against a large set of predicates, it's nice to be able to encapsulate the predicates like this. The ability to programmatically add or remove predicates from the list truly extends the versatility of this construct beyond what you can (easily, naturally) do with if/elif/elif.
This particular set of predicates can't all be true for a single number. Maybe you want any() instead of all()...?
Your "conditions" are functions mapping the input to booleans. Therefore, you can write them as functions:
def is_small(number):
return number < 9
def is_large(number):
return number > 20
conditions = (is_small, is_large)
Then you can evaluate all of these functions on some input:
def check_all(input, conditions):
return [condition(input) for condition in conditions]
check_all(10, conditions)
>>> [False, False]
And if you want to know if all of these or any one of these are true, you can use the functions all and any:
any(check_all(10, conditions))
>>> False
any(check_all(21, conditions))
>>> True
And not all(…) is True if one of the conditions is not fulfilled, not any is True if none is.
Edit: One thing to notice is that the list comprehension [… for … in …] in check_all always evaluates all functions. This is not necessary if you use any or all, which can use an iterator and stop evaluating it onces the result it fixed (at the first True for any and the first False for all). If you use them, you can just replace the list comprehension [… for … in …] by a generator expression (… for … in …).
You could create a tuple of booleans and check it via all.
conditions = []
conditions.append(yourVar < 9)
conditions.append(yourVar > 20)
conditions.append(yourVar <= 3)
if all(conditions):
print('All conditions are met')
else:
print('At least one condition results in false)

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

Several arguments in if statement

I have a script that relies on argparse. The mainbody of the script has if statements like this:
if results.short == True and results.verbose == False and results.verbose2 == False and results.list == False and results.true == False:
Isn't there any shorter way to do that? Say I have more than those 5 arguments, typing each of them in every statement seems like repetitive work.
Can't if do something like:
if results.short == True and "results.%s"== False % (everyotherresults.something):
I'm writing for Python 2.7
you shouldn't compare to bool in boolean expressions, eg:
if (results.short
and not results.verbose
and not results.verbose2
and not results.list
and not results.true):
You can use any function on list, and move all your arguments from 2nd in a list: -
if results.short and \
not any([results.verbose, results.verbose2, results.list, results.true]):
any function returns True if at least one value in the list is True. So, just use not any, which will return True if all the values in the list is False.
And yes, you don't need to compare boolean value with True or False.

Categories

Resources