My code is checking only 1 if condition in a function [duplicate] - python

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

Related

Not Printing anything on screen

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.

I can't figure out what is wrong with this function?

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!

Function that checks if brackets are balanced in python

I have written the following code to check if some input to the function contains balanced brackets:
def balanced_brackets(text):
brackets = [ ('(',')'), ('[',']'), ('{','}'),('<','>')]
s = 0
e = 1
st = Stack()
for i in text:
for pair in brackets:
if i == pair[s]:
st.push(i)
elif i == pair[e] and not st.isEmpty() and st.pop() != pair[s]:
return False
if st.isEmpty():
return True
else:
return False
This code is working for input such as '()(())()' but it failed when I tried it for 'zn()((b)())q())()l()d(r)'. Can anyone help me identify what the problem is? Thanks.
Your problem is with the and not st.isEmpty()==0. When it gets to the unbalanced ')', all the previous ones have balanced out, so st is empty.
If you have a i == pair[e], and your stack is empty, you want to return False.
You also want to return False if you pop and it isn't pair[e]. But you don't want to pop if the stack is empty.
What you have now, in condition 1, just keeps going. You need to change around the condition there so that it accounts for both, or have two elifs. The former can be achieved with some nesting ands and ors.
By the way; unless you want to do something fancy with it, there's no real need to implement a stack. You can just use a list instead, with l.pop, len(l), and l.append.
This works.It needs a stack module to import. It will keep track of matched pairs.
def multi_bracket_validation(input):
""" test for matching brackets and return bool """
if type(input) is str:
open_b = '({]'
closed_b = ')}]'
compare = Stack()
for brac in input:
if brac in open_b:
compare.push(brac)
elif brac in closed_b:
if compare.top is None:
return False
if closed_b.index(brac) != open_b.index(compare.pop().val):
return False
return compare.top is None
return False

Sorted values in increasing order and adjacent values

In python, I am trying to check if a given list of values is currently sorted in increasing order and if there are adjacent duplicates in the list. If there are, the code should return True. I am not sure why this code does not work. Any ideas? Thanks in advance!!
def main():
values = [1, 4, 9, 16, 25]
print("Return true if list is currently sorted in increasing order: ", increasingorder(values))
print("Return true if list contains two adjacent duplicate elements: ", twoadjacentduplicates(values))
def increasingorder(values):
hlist = values
a = hlist.sort()
if a == hlist:
return True
else:
return False
def twoadjacentduplicates(values):
ilist = values
true = 0
for i in range(1, len(ilist)-1):
if ilist[i] == ilist[i - 1] or ilist[i] == ilist[i + 1] :
true = true + 1
if true == 0:
return False
if true > 0:
return True
main()
Your increasingorder function will almost certainly not work, because Python uses references, and the sort function modifies a list in-place and returns None. That means that after your call a = hlist.sort(), both hlist will be sorted and a will be None. so they will not compare equal.
You probably meant to do the following, which will return a sorted list instead.
a = sorted(hlist)
This function works:
def increasingorder(values):
hlist = values
a = sorted(hlist)
if a == hlist:
return True
else:
return False
You can of course simplify this down to a single line.
def increasingorder(values):
return sorted(values) == values
Your second function looks logically correct, but can be simplified down to the following.
def twoadjacentduplicates(values):
for i in range(0, len(values)-1):
if values[i] == values[i + 1] :
return True
return False
Try creating a True False function for each value check operation you want done taking the list as a parameter. then call each function like "if 1 and 2 print 3" format. That may make thinking through the flow a little easier.
Is this kind of what you were wanting?
def isincreasing(values):
if values==sorted(values):
return True
return False
def has2adjdup(values):
for x in range(len(values)-1):
if values[x]==values[x+1]:
return True
return False
if isincreasing(values) and has2adjdup(values):
print "True"

if True and if False statements

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

Categories