Not Printing anything on screen - python

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.

Related

I cannot figure out how to fix this problem, can someone help me ? Pirple homework python

Create a global variable called myUniqueList. It should be an empty list to start.
Next, create a function that allows you to add things to that list. Anything that's passed to this function should get added to myUniqueList, unless its value already exists in myUniqueList. If the value doesn't exist already, it should be added and the function should return True. If the value does exist, it should not be added, and the function should return False;
extra is if we can make the remaining values to a list called my leftovers
myUniqueList = []
myLeftovers = []
def addUniqueElement(b):
if b not in myUniqueList:
print(myUniqueList.append(b))
return True
else:
myLeftovers.append(newElement)
return False
print(addUniqueElement())
Something to note is that your attempt was very good. It did everything right except for a few things:
You should print out the list if you want to see the final list
eg.
print(myUniqueList)
Next, the function requires an argument, in this case, I'll use "cool"
so now we have
addUniqueElement("cool")
print(myUniqueList)
In the end we get
myUniqueList = []
myLeftovers = []
def addUniqueElement(b):
if b not in myUniqueList:
print(myUniqueList.append(b))
else:
myLeftovers.append(newElement)
addUniqueElement("cool")
print(myUniqueList)
print(myLeftovers)
There's no point in printing when you call myUniqueList.append(b). It just updates the list, it doesn't return anything.
You need to pass an argument when you call the function.
newElement should be b.
def addUniqueElement(b):
if b not in myUniqueList:
myUniqueList.append(b)
return True
else:
myLeftovers.append(b)
return False
print(addUniqueElement(1)) # True
print(addUniqueElement(2)) # True
print(addUniqueElement(1)) # False
print(addUniqueElement(5)) # True
print(addUniqueElement(10))# True
print(addUniqueElement(5)) # False
print(myUniqueList) # [1, 2, 5, 10]
print(myLeftovers) # [1, 5]
here you can continuously add text (ex numbers ) and watch them being added to the one or to the other list
myUniqueList = []
myLeftovers = []
def addUniqueElement(text):
if text not in myUniqueList:
myUniqueList.append(text)
return True
else:
myLeftovers.append(text)
return False
while ( 1 ):
text = input("text: ")
addUniqueElement(text)
print("myUniqueList: ", myUniqueList)
print("myLeftovers: ", myLeftovers)

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

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 not able to fix a code issue in python

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.

Python: Why else statement can be discarded in this simple expression?

I apologize for how obvious this answer must be, but I just can't seem to find out why an else statement isn't needed in the following function which returns True -
def boolean():
x = 1
if x == 1:
return True
return False
boolean()
My beginner coding mind is confused why False isn't being returned. The if statement returns True, then outside of that if statement, False is returned. I would've thought to write -
def boolean():
x = 1
if x == 1:
return True
else:
return False
boolean()
Why isn't the else statement needed here? Thank you very much for enlightening me on this.
The execution of a function always ends as soon as a return statement is run. Nothing past that point is even evaluated. For example, if you added a print statement immediately after the return statement, you would not see it printed in the console.
Similarly, the execution of this function never reaches return False because True was already returned.

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