Python - if not condition returning None - python

This is another question from https://stackoverflow.com/questions/41028828/python-does-if-not-statement-implicitly-check-2-conditions?noredirect=1#comment69265422_41028828
I am trying to further clarify the concept with ifstatement using not.
My understanding is that print secondFunction(True) will return True since randomFunction will be called but the script is returning None. Please help!
def randomFunction(value):
if value:
return True
else:
return False
def secondFunction(v):
if not randomFunction(v):
return "minus it"
print secondFunction(True)

"randomFunction" returns True to "secondFunction". At this point you have this "if" condition:
if not (True):
If it would be "True" condition was verified and "secondFunction" returns "minus it". In your example it will never enter inside the "if" condition. For this reason "secondFunction" will always return None result because it has became implicitly a procedure without a return.
I hope that was clearly to you.

Related

Is it better to use 'elif' or consecutive 'if' statements alongside return statements?

This question is specifically regarding coding convention. I know that using if or elif in this case will produce the same results. Just wondering which is the "proper" way to construct this function:
With consecutive if:
def can_take(self, selectedCourse):
if selectedCourse.hasPassed():
return False
if selectedCourse.getPrereqs() != 'none':
for prereq in selectedCourse.getPrereqs():
if not self.courses[prereq].hasPassed():
return False
return True
With elif:
def can_take(self, selectedCourse):
if selectedCourse.hasPassed():
return False
elif selectedCourse.getPrereqs() != 'none':
for prereq in selectedCourse.getPrereqs():
if not self.courses[prereq].hasPassed():
return False
return True
If I had to choose between the two, I would probably use two if statements, but that's just a matter of personal preference.
If I had a third choice, I wouldn't have any return statements with Boolean literals. I would write a single return statement that uses and and or.
return (not selected.hasPassed()
and (selected.getPrereqs() == 'none'
or all(x.hasPassed()
for x in selected.getPrereqs()))
This is close to how you would describe this in English: you can take the class if you have not passed it, and if the class either has no prerequisites or if you have passed all the prerequisites.
As John Kugelman points out, if getPrereqs returned an empty list instead of 'none', you could further reduce this to
return (not selected.hasPassed()
or all(x.hasPassed()
for x in selected.getPrereqs())
I love the early return pattern:
Get invalid cases out of the way first, either simply exiting or raising exceptions as appropriate, put a blank line in there, then add the "real" body of the method. I find it easier to read.
Returning early keeps the nesting level down, which is great way to reduce cognitive load. I would take it one step further and flip the second if statement around so it too returns early:
def can_take(self, selectedCourse):
if selectedCourse.hasPassed():
return False
if selectedCourse.getPrereqs() == 'none':
return True
for prereq in selectedCourse.getPrereqs():
if not self.courses[prereq].hasPassed():
return False
return True
That said, some other improvements I would make:
Avoid stringly typed variables. Switch that 'none' to None.
But then, when a method returns a list don't return None when there are no results. Return an empty list. Then the caller can blindly iterate over the list without checking if it's None or empty.
def can_take(self, selectedCourse):
if selectedCourse.hasPassed():
return False
for prereq in selectedCourse.getPrereqs():
if not self.courses[prereq].hasPassed():
return False
return True
If you're comfortable with generator expressions you could even convert the loop into an all(...) call, removing the need for the final return True.
def can_take(self, selectedCourse):
if selectedCourse.hasPassed():
return False
return all(self.courses[prereq].hasPassed()
for prereq in selectedCourse.getPrereqs())
I like this because it's a more direct encoding of the question: "Has the student passed all of the prereqs?"
I think I prefer the first version. Why? When you have an if...elif...elif... thing with returns in each branch, there are two "competing" control structures: the if statement and the returns. Obviously, the returns will "win", so we might as well remove the elif stuff. Either that, or have just one return statement, which returns a value computed by a preceding if...elif...elif...else structure.
We use elif but please understand it depends on your problem statement.
Note: Please do not create a big ladder out of it as then it becomes difficult to maintain and debug the code.

Python: Why do we use boolean values in functions to return print statement in our main program?

quick question since I was not able to find a sufficient answer online.
Following code snippet:
def Credentials (x, y):
list = [("test", 1234), ("test2", 4567)]
for list in list:
if list[0] == userinput1 and list[1] == userinput2:
print("success")
return True
else:
print("error")
return False
userinput1 = str(input("provide username: "))
userinput2 = int(input("provide PW: "))
Credentials(userinput1, userinput2)
I do not fully understand why the boolean values True and False will return the print statements. I know that we use return statements to work with functions in our main program and that we could also define variables and return those. But why exactly does returning the booleans will give us the print outputs?
Many thanks in advance.
Short answer: It does not
In your function/in my function shown below,
def returnBools():
(print) print('Printed')
(return) return True
print(returnBools())
The print function and the return statement are actually two different things. The print has nothing to do with the return, and the return statement does not in anyway trigger the print function.
Additionally, the way we call the function can effect the output
For example, printing the function print(returnBools()) will display the returned value along with any print functions in our function
output
Printed
True
But say we did not print the function and only called it. returnBools(). The returned value will not be showed in this case and only the printed values will.
output
Printed

Exit function based on the return parameter of an another function?

I'm trying to understand the logic of this code below. Could someone please help me on below questions?
1) Does the for loop continues execution because of the return of check_cheese is False? As far as I know, either the outcome is True or False, a return command stops the execution of a function.
2) Does the if check_cheese(cheese) statement returns cheese variable only if the return parameter of check_cheese() function is True? I'm a bit confused here because there is no check like == or in or any other statement that indicates to return cheese only if the condition is True.
3) What would be the case if Gouda is not existent in the list? Is it going to be like every condition in the for loop returns False and at the end print statement you call yourself will be executed before termination?
Thanks in advance for any help you are able to provide.
def check_cheese(cheese):
if cheese == "Gouda":
print("ooh we have that one")
return True
print(f"we don't have any {cheese}")
return False
def find_first_available_cheese():
for cheese in ['Emmental','Gouda']:
if check_cheese(cheese):
return cheese
print("and you call yourself a cheeseshop!")
find_first_available_cheese()
A call to a return statement will always break the outer loop / function, even if it is return False. In your case, the if condition is preventing to call the return statement
Your check_cheese function never returns a cheese variable, only booleans
Why don't you try? ;)
1) Does the For loop continues execution because of the return of
check_cheese is False? As far as I know, either the outcome is True
or False, a return command stops the execution of a function
If you return inside of an if-statement, it will break from the function.
2) Does the "if check_cheese(cheese)" statement returns cheese
variable only if the return parameter of check_cheese() function is
True? I'm a bit confused here because there is no check like "==" or
"in" or any other statement that indicates to return cheese only if
the condition is True.
The for loop runs until it finds a Gauda cheese, as indicated in the check_cheese function.
3) What would be the case if Gouda is not existent in the list? Is it
going to be like every condition in the for loop returns False and at
the end print statement "you call yourself" will be executed before
termination?
You'd get a printout "And you call yourself a cheese shop!". Try. :)

Python print None

I'm having trouble with print None as a value.
Suppose here's my python code:
def a(b):
b = None
print b
def c(a):
if a:
return True
else:
return False
>>> a(1)
None # I need this "None" to show.
>>> c(a(1))
None # I don't want to print out this, but don't know how.
False
My problem is I have to "print" the None when only calling function a.
And when I pass function a to function c, I don't want the "None" to print out.
If I type "return None", Python shell will not show "None" for function a. That's why I thought I can only use "print" if I want to show the "None". But when I pass function a to function c, the "None" also gets printed out. Is there a way to only get the result secretly without printing out the "None" in the 2nd function?
I hope my question is making sense.
Thank you very much for your help.
The call c(a(1)) will execute a(1) first and then c(a(1)). Since here a(1) is not returning true, c(a(1)) will evaluate to False.
That's the reason you get following:
None
False
Try calling the function as c(a) this will return as follows:
True
This happens because a has not executed and it is having some value to it.
Hope this helps!

Python: How to print a value that is returned

I am working on a program that solves a physics question, and I am stuck.
My question is, how can I print a value that is returned?
For example:
(suppose u is the input, which is a list)
def solver(u):
if (u[6]*g*sin(u[0])) > (u[6]*g*cos(u[0])*u[3]):
x1total = (1.0/2.0)*g*sin(u[0])*u[9]*u[9]
return x1total
else:
x1total=0
return x1total
if (u[7]*g*sin(u[1])) > (u[7]*g*cos(u[1])*u[3]):
x2total = (1.0/2.0)*g*sin(u[0])*u[9]*u[9]
return x2total
else:
x2total = 0
return x2total
print [x1total,x2total]
solver(u)
Now, what I expect is to get the outputs as a list. However, I get nothing. Help me please. Thanks in advance.
Your function never makes it to the print statement because all possible cases hit a return.
Remove all of the return statements and it should print ok.
Your print statement is after the return statement.
The return statement causes the execution of the function to be stopped. The value specified in the statement is returned to the caller.
To get the returned value, you do this:
value = solver(u)
Then you can:
print value

Categories