I've always been confused about using True and False on if statements. For instance, let's say that I've defined a function that returns True or False.
def isEven(number):
if number % 2 == 0:
return True
else:
return False
Now I need to use that function on one of my code which can only proceed if the number is even. I believe I have seen codes like if isEven(number): proceed etc etc, my question is, is it considered True by default? Or should I keep using if isEven(number) == True
When you have something like that :
if myboolean : ...
it means "if myboolean is true, then do whatever is after". So it's the same as :
if myboolean==true : ...
Both uses are exactly the same. In
if expr:
pass
first expr is evaluated so you get
if True:
pass
or
if False:
pass
no matter what the original expr was.
PS:
Now, I always found the if True: return True pattern obsolete. Why not return True directly. That is:
def isEven(number):
return (number % 2 == 0)
You should just use
if isEven(number):
# proceed
It only has a possible different meaning if isEven doesn't return True or False
For example 1, 2, 3 etc. are treated as True
None, 0, [] etc are treated as False
Additionally, you have the same type of redundancy in your function
def isEven(number):
return number % 2 == 0
works just as well. The following works too, but is less clear
def isEven(number):
return not number % 2
if isEven(number):
will execute the indented code after if when isEven returns True
You don't need to check isEven(number) == True
Related
def even_number_list(even_list):
for i in even_list:
if i % 2 == 0:
return True
else:
pass
even_number_list([1,3,5,6,9])
This code is not printing anything on the screen, I believe that it should print True, please help a beginner.
Thanks,
I think I'll get an output, True
Your function, as you expect, should return True. But when you call it, you don't use the return value. If you want to print the return value, you need to call even_number_list() inside of a print() function to print the output or assign the function call to a variable.
def even_number_list(even_list):
for i in even_list:
if i % 2 == 0:
# Return True if one even number is found
return True
# Return False if all numbers in even_list are odd
return False
# Call function even_number_list() returns True but is not assigned to anything
even_number_list([1,3,5,6,9])
# Assign return value to output
output = even_number_list([1,3,5,6,9])
# Print the output
print(output)
# Or in one step:
print(even_number_list([1,3,5,6,9]))
I also removed your else condition, as the pass statement does nothing.
And in addition, if no even number is found your function returns False now.
This is what it should return
Returns True if all items are truthy.
Examples:
>>> all_true([1, True, 'oregonstate'])
True
>>> all_true([0, 1, 2])
False
"""
This is what I have written
def all_true(items):
for i in items:
if i == True:
return True
else:
return False
pass
Not sure why it is not working, can someone help?
Your function just returns the truthiness of the first item in the list, since it always returns on the first iteration.
You want to do something like this:
def all_true(items):
for i in items:
if not i:
return False
return True
Note that this all_true function already exists in Python. It is the the built-in all function.
Two problems. First, you are returning on the first True thing. In fact, you are returning either True or False on the first thing, regardless. Since you return on both the if and its else clauses, the loop will always return on the first iteration. A bit more subtle, but if there aren't any values in the list, it will return None.
Second, if you want "truthy", don't compare specifically to True. foo == True is False. Instead, just let the if do the boolean test
def all_true(items):
for i in items:
if not i:
return False
return True
all and any are builtin functions that do the same thing. It would generally be preferable to use them.
"All items are truthy" is logically equivalent to "no items are falsy."
def all_true(items):
for i in items:
if not i:
return False
return True
Because 0 is falsy. Also there's no need to implement your own function for that, use Python's built–in all() function instead!
This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 3 years ago.
def check(str):
if(str.isalnum())==True:
return True
if(str.isalpha())==True:
return True
if(str.isdigit())==True:
return True
if(str.islower())==True:
return True
if(str.isupper())==True:
return True
if __name__ == '__main__':
s = input()
if(check(s)):
print('True')
else:
print('False')
It is showing only one condition's result. For example, if I type qA2 it is showing one True instead of
True
True
True
True
True
This is because you are "returning" from the function if one of the if conditions evaluates to true.
You can read more about the keyword return here.
The gist is, as the word says, it "returns" from the function with specified value(s).
If you want the other if conditions to get evaluated too, you will need to maintain a small data structure of all successful if conditions, eg:
def check(str):
# let's initialise a dictionary with all False values.
# If any if condition turns True, then we will set
# that value to True in the dictionary.
res = {
"isalnum":False,
"isalpha":False,
"isdigit":False,
"islower":False,
"isupper":False,
}
if(str.isalnum())==True:
res["isalnum"] = True
if(str.isalpha())==True:
res["isalpha"] = True
if(str.isdigit())==True:
res["isdigit"] = True
if(str.islower())==True:
res["islower"] = True
if(str.isupper())==True:
res["isupper"] = True
return res # This returns a dictionary with all values
if __name__ == '__main__':
s = input()
if(check(s)):
print('True')
else:
print('False')
return leaves the function immediately. The first condition which succeeds will cause the rest to be skipped, the way you defined your function.
If you want to check all the conditions every time, try something like
def check(str):
whether = True
if not str.isalnum():
whether = False
if not str.isalpha():
whether = False
if not str.isdigit():
whether = False
if not str.islower():
whether = False
if not str.isupper():
whether = False
return whether
Printing something in each branch seems excessive, but could certainly be added.
return stops the function's execution. Nothing after a return statement will be run, and a function can only have a single return value. If you want to see the result for all conditions, store them in a List or a Dict and return that instead, for example:
def check(str):
results = {}
results['isalnum'] = str.isalnum()
results['isalpha'] = str.isalpha()
results['isdigit'] = str.isdigit()
results['islower'] = str.islower()
results['isupper'] = str.isupper()
return results
I am trying to define 2 functions, but only has_33 is working and myfunction is not working.
I am trying this code in jupyter notebook:
def myfunction(num):
for i in range(0, len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
and this code:
def has_33(nums):
for i in range(0, len(nums)-1):
if nums[i:i+2] == [3,3]:
return True
return False
myfunction([1,2,4,3,3]) should give true but it is giving false result but has_33([1,2,4,3,3]) is giving the true result. Why is this happening?
Hi there is indent difference in both code:
in first function second return is inside of for loop where as in second function it is out of for loop:
So in first function when if condition is false and it is going on second return and returning false for first value 0
In second function if evaluation keep false till i is 3 and for loop is not executing return. Once if evaluation become true on i=0 it is executing return of if and returning true so control goes out of function and second return out of for is not getting executed:
corrected first function:
def myfunction(num):
for i in range(0,len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
Indentation error! Just needed to erase a whitespace from the last line of your first code. The for loop will return False now. Try like this:
def myfunction(num):
for i in range(0,len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
Posting my comment as an answer as suggested by #quamrana.
This behavior is because of indentation. In myfunction, if the condition nums[0:2] == [3,3] is not satisfied, then the function immediately returns False. Whereas in has_33, it iterates through entire list and then only will return False if there are no consecutive [3,3].
e.g.
nums = [1,2,3,3,5]
myfunction(nums)
False
Let's go step by step in the function
for i in range(0,len(num)-1)
i is initialized to 0, i.e. i = 0.
nums[i:i+2]
Since i is 0, becomes nums[0:2] i.e. [nums[0], nums[1]].
if num[i:i+2] == [3,3]
Becomes if num[0:2] == [3,3]. Since nums[0] = 1 and nums[1] = 2, [nums[0], nums[1]] != [3,3]. Thus, if block will not be executed.
Since return False is in the for loop and if condition was not satisfied, the next line is executed, which is return False. The function execution stops here.
Now, second function:
nums = [1,2,3,3,5]
has_33(nums)
True
Step by step
Same as myfunction.
Same as myfunction.
Same as myfunction.
Now here is the catch. Since return False is written outside for loop, i increases by 1.
i = 1
nums[i:i+2] is nums[1:3] which is [nums[1], nums[2]].
The loop continues until you get a [3,3] OR i = len(nums) - 1.
Hope this helps you understand what went wrong.
The last point of the style guide http://www.python.org/dev/peps/pep-0008
reads ...
Don't compare boolean values to True or False using ==.
Why?
Edit
Just to make it clear what im asking (and it's indicative of the problem itself), when you write
if something:
print "something is true"
You are doing an implicit conversion to a boolean which may or may not work depending on what true means. IMHO this form of programming is discouraged because of the side effects it can cause.
numberOfApples = -1
if numberOfApples:
print "you have apples" # is not what is intended.
if numberOfApples == True:
print "you have apples" # is also not what is intended.
iHaveApples = numberOfApples > 0
if iHaveApples is True: # Edit: corrected this.. the "is" is better than the ==
print "you have apples" # is correct.
Implicit conversions disguise logical errors. So why does the style guide encourage this?
It means that you should write
if greeting:
Instead of:
if greeting == True:
Similarly, you shouldn't write this either:
if (greeting == True) == True:
The extra tests are redundant and don't add any value to the code, so they should be removed.
IMHO the point of a style guide is to standardise some common constructs, in a way that makes sense, so you won't end up with wildly disparating statements that ultimately do the same thing. More, the unusual forms might suggest that the programmer had some reason to do things a different way, maybe he was trying to achieve something different than what the statement looks like.
If you want to test the truehood/falsehood of a statement, just use the statement itself or precede it by not. If you must ensure the statement evaluates to True or False (not just a truthy/falsy value), you could use statement is True - though the style guide discourages it - or maybe check its type (using isinstance). But that's usually bad design, you should avoid that unless you have a pretty good reason to do so.
Using statement == True is dangerous for many reasons: 1) only work with True, failing with other "truthy" values (like [1]); 2) might produce unexpected results if the value returned by statement redefines __eq__; 3) might produce different results if the order of the arguments is changed, etc. Note that just using the statement may also return a different value for truehood/falsehood if the value implements __nonzero__ or __len__, but for regular usage that's usually not a problem.
Some examples showing how messed up things can be if you deviate from the style:
if True: print True # True
if 1: print True # True
if [1]: print True # True
True is True # True
1 is True # False
[1] is True # False
True == True # True
1 == True # True
[1] == True # False
Edit: some more:
if 1: print True # True
if 2: print True # True
1 == True # True
2 == True # False
1 is True # False
2 is True # False
Update: as #Marcin pointed out, you can use bool to coerce a value to True/False, guaranteeing that only those values will be present. The result of that function is consistent to the default truehood/falsehood of the value (so __nonzero__ and __len__ is taken into account). Some examples:
if bool(1): print True # True
bool(1) == True # True
bool(1) is True # True
if bool(2): print True # True
bool(2) == True # True
bool(2) is True # True
1 or 2 # 1
1 and 2 # 2
bool(1) or bool(2) # True
bool(1) and bool(2) # True
bool(1) == bool(2) # True
bool(1) is bool(2) # True
Because it's redundant.
if hasChildren:
is the same as
if hasChildren == True:
but is briefer and easier to read.
In sort:
# A, Good:
if numberOfApples > 0:
print "you have apples"
# B, Also good:
iHaveApples = numberOfApples > 0
if iHaveApples:
print "you have apples"
# C, Bad:
iHaveApples = numberOfApples > 0
if iHaveApples == True:
print "you have apples"
Why would you ever pick C over A or B?
Update:
I think you're sweating bullets over some corner cases, but if those corner cases matter in your project use the appropriate comparison. In general we do know something about the type of iHaveApples, for example we know that it's the result of a comparison using >. It's reasonable, and good practice I believe, to use that information in your code. If you're asking, "what if I think it's a bool and it turns out to be an int or something else." Than I would say you have a bug in your code, you should find it, fix it, and write a test in case you make the same mistake again. Don't rely on python to find your mistakes at runtime.
I'll assert, and leave up to you to prove if you want, that if iHaveApples: behaves exactly the same, but runs faster, as if iHaveApples is True: when you know for sure that iHaveApples is a bool. Lastly I'll give an example of when is would result in undesired behavior, at least in my opinion.
>>> import numpy
>>> totalApples = numpy.sum([1, 2, 3]) == 6
>>> totalApples
True
>>> totalApples is True
False
I'll let you figure out why that doesn't work if you want (hint, check type(totalApples)).