Why is this displaying None? - python

def characterLine(firstChar,secondChar,phrase):
'\n' + ((str(firstChar)+str(secondChar))*(len(phrase)/2)+len(phrase)%2* firstChar)
So the second part of the code will display but when I try to concatenate it with a line skip, it displays "None."
Can someone explain to me as to why this is happening?

if you are trying to print the return value of characterLine(..), i.e.
print characterLine(...)
this will print None because you are not using the return keyword in front of your expression. Setting
def characterLine(firstChar,secondChar,phrase):
return '\n' + ((str(firstChar)+str(secondChar))*(len(phrase)/2)+len(phrase)%2* firstChar)
should return a value other than None (which you then can print).

Be default, functions have an implied return None as the end.
An empty return-statement also returns None.
So, you just need to add the return-statement to your function. Otherwis, the rest of it looks okay. Good luck :-)

Related

How to fix inconsistent return statement in python?

I am new to python and i have this project I am working on a small project with two functions where the first returns the index of the first time a difference is spotted in a string. The next function does that but in a list of strings. Now, due to my being an amateur, i have used an excessive amount of if and else statements which resulted in too many return statements especially in the second function, and i get the error [R1710: inconsistent-return-statements]. How do i fix it and can anybody give me clear examples to better pieces of code? Sorry for the question being so long.
IDENTICAL = -1
def singleline_diff(line1, line2):
"""
Inputs:
line1 - first single line string
line2 - second single line string
Output:
Returns the index where the first difference between
line1 and line2 occurs.
Returns IDENTICAL if the two lines are the same.
"""
len1 = len(line1)
len2 = len(line2)
minimum_length = min(len1, len2)
if len1 != len2:
if minimum_length == 0:
return 0
for idx in range(minimum_length):
if line1[idx] == line2[idx]:
pass
else:
return idx
return idx + 1
for idx in range(len1):
if line1[idx] == line2[idx]:
pass
else:
return idx
return IDENTICAL
def multiline_diff(lines1, lines2):
"""
Inputs:
lines1 - list of single line strings
lines2 - list of single line strings
Output:
Returns a tuple containing the line number (starting from 0) and
the index in that line where the first difference between lines1
and lines2 occurs.
Returns (IDENTICAL, IDENTICAL) if the two lists are the same.
"""
line_no = singleline_diff(lines1, lines2)
len_lines1, len_lines2 = len(lines1), len(lines2)
if len_lines1 == len_lines2:
if (len_lines1 or len_lines2) == 0:
if len_lines1 == len_lines2:
return (IDENTICAL, IDENTICAL)
else:
idx = singleline_diff(lines1[line_no], lines2[line_no])
return (line_no, idx)
else:
idx = singleline_diff(lines1[line_no], lines2[line_no])
if line_no == IDENTICAL:
return (IDENTICAL, IDENTICAL)
elif line_no != IDENTICAL:
return (line_no, idx)
else:
return (line_no, 0)
Where was a semantic mistake in OP's code is in Abhishek Arya's answer
TL;DR - early return:
def your_function():
if not should_do():
return # NO RETURN VALUE!
# rest of the function
...yes, this will no longer emit the inconsistent-return-statements ;)
This Q/A pops also when you search for inconsistent-return-statements, I want to give a brief "common problems" guide for those.
Case A: return value is irrelevant, you just want to exit function early
There are cases, where there are functions (or "procedures" if you want to get technical about it) that just do something, but are not expected to have any return values AT ALL,
at the same time, there may be e.g. some sort of check at the start of the function whether this function run even makes sense, what may first come to your mind, is wrapping the whole function code in an if statement:
def your_function(article):
if display_content():
content = get_content(article)
# do some extensive logic to generate final content
# ...
print(content)
...this is oversimplified, but let's hope you can imagine how such coding can pretty quickly fall into a "spaghetti code" if there are more checks and more code in general + it also steals that one "tab" of a space that you so desperately need to fit into your project's max line length.
Luckily, same as in many other programming languages, there IS a way of an early ending of a function by returning at ANY place within the function run, meaning in any "Control Flow" - including if/elif/else, for/while loops, ...
Now you'd probably jump quick to just return None, False, etc. although it would work, you'd still get the pylint inconsistent-return-statements warning - to understand why let's see the warning's message:
Either all return statements in a function should return an
expression, or none of them should. pylint(inconsistent-return-statements)
From pylint's point of view, if you put anything after the return it will be considered as an expression. So what to do? Actually, in Python, you CAN return "nothing" (again this is not unique to Python)
def your_function(article):
if not display_content():
return
content = get_content(article)
# do some extensive logic to generate final content
# ...
print(content)
Although in Python returning "nothing" should be (and technically, to my knowledge, it is) an equivalent of return None, by physically writing "None" you are expressing the intention no matter the implicity of it.
Don't confuse this though with pylint(assignment-from-none) (Assigning result of a function call, where the function returns None) - where both "return" AND "return None" are considered as returning None!
Case B: Your function has a case when it doesn't return
Quite common mistake especially in a larger code is to create a code part which results in simply not returning anything. This is not exactly OP's case, since they used just a negation of the same condition, but pylint doesn't know that, so here's its thought process:
if SOME_CONDITION: # ok, here's just another condition
return someReturnExpression # and ok, it returns SOMETHING, let's note that
elif OPPOSITE_OF_SOME_CONDITION: # ok, here's just another condition
return someReturnExpression # and ok, it returns SOMETHING, let's note that
# WAIT ! What?! THERE WAS NO "else:"! Hmmm...
# ...what happens if both conditions fail? NOTHING WOULD BE RETURNED!
# We need to make a warning about that!
# (fact that sometimes they return SOMETHING and sometimes NOTHING)
So this inconsistent-return-statements could be resolved with
if SOME_CONDITION: # ok, here's some condition
return someReturnExpression # and ok, it returns SOMETHING, let's note that
else: # ok, here's else
return someReturnExpression # and ok, it returns SOMETHING, let's note that
# Ok, so if returns SOMETHING, else returns SOMETHING,
# so SOMETHING is returned every time! that's good!
...this in itself works, but it will generate yet another pylint issue
Unnecessary "else" after "return" pylint(no-else-return)
See python actually encourages early returns since it often leads to a cleaner code.
return during function run ENDS(/exits) the function and pylint sees that - it sees that if the condition was true, the function code would simply end there - so what it, Abhishek Arya, me and many others suggest is simply continuing with the code after the if part:
if SOME_CONDITION:
return someReturnExpression
# ... some more code ...
# ... some more code ...
return someReturnExpression
Case C: Combination
Simply don't combine "just" return with return SOMETHING,
if you really need to return None, simply explicitly return None in that case
def get_article(id):
article = find_article(id)
if article.id == 0:
return None
return article
This is just an example, this is not how you'd really check for some articles ;)
Look at the code here:
if len_lines1 == len_lines2:
return (IDENTICAL, IDENTICAL)
else:
idx = singleline_diff(lines1[line_no], lines2[line_no])
return (line_no, idx)
You could have written the above thing like:
if len_lines1 == len_lines2:
return (IDENTICAL, IDENTICAL)
idx = singleline_diff(lines1[line_no], lines2[line_no])
return (line_no, idx)
You just don't need an else block to return this expression as this part of code will automatically be called if the control doesn't go into if block. Hope it 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

No result returned during recursion

So I was creating a simple recursive function which essentially compares two strings, 'string' and 'target', and if they're the same, the function replaces the 'target' with 'rep', much like the function of find and replace you would see in a text editor. My issue is, is that the function returns nothing. Is that because it hasn't hit my base case or am I missing an extra return somewhere?
def helperfn(string,target,rep,x): # x is always initially set to zero
if x==len(string): #base case
target=rep
return target
if len(string)==len(target):
if string[x]==target[x]:
helperfn(string,target,rep,(x+1))
else:
return "string and target are not the same"
A few examples of what the expected output should be:
helperfn("noway","noway","yes",0)=>"yes"
helperfn("ok","ok","never",0)=>"never"
When you call the function recursively, you want to return that value.
return helperfn(string,target,rep,(x+1))
It's because you never returned anything explicitly in one branch. Change
if len(string)==len(target):
if string[x]==target[x]:
helperfn(string,target,rep,(x+1))
to
if len(string)==len(target):
if string[x]==target[x]:
return helperfn(string,target,rep,(x+1))

can't do return function in condewrite

I'm trying to understand the difference between returning and printing (I get the theory behind it, but when actually designing the code, I'm a bit lost as to how they're different from each other). I'm trying to repeat the middle character in an inputted string coupled with a repetition (int).
Why doesn't this work? Either in python idle or ion codewrite?
def mid_repeated (st, rep):
if len(st)%2==0:
middle = (len(st)/2)
center = (st[middle])*rep
rep = "!"*rep
return center + " " + str(rep)
else:
middle = (len(st)/2)
center = (st[middle])*rep
rep = "!"*rep
return center + " " + str(rep)
return mid_repeated
As soon as a function returns something, it breaks. This is probably what you're wondering about.
However, I'm not exactly sure what you're trying to accomplish by returning the function itself. You may want to look at that again.
I'm not sure if this helps at all, but return, returns something that can then be used outside of the function, where as print, just prints something...
The difference between
def a(x):
print x
and
def b(x):
return x
is that they do different things. (No. Really?)
a() outputs the "thing" given as x and (implicitly) returns None.
b() does nothing but returning x.
The difference becomes clearer if you do
def examine(function):
print "Calling:"
ret = function(42)
print "Call done."
print "Function returned", ret
if I use this function to examine my functions,
examine(a)
prints
Calling:
42
Call done.
Function returned None
so you clearly see that the 42 is printed while the function runs and the function's return value is None.
OTOH,
examine(b)
prints
Calling:
Call done.
Function returned 42
which proves that the function prints nothing but giving the value provided back to the caller (as a return value), who is able to print it whenever appropriate, or do anything else with it.
Other point of view: print prints the given value immediately, return just gives it to the caller to do whatever is desired.

Python: "return <tuple>" keeps returning None

I have the following code:
def subStringMatchExact(target,key,matches=(),base=0):
if find(target,key) != -1:
matches += (find(target,key)+base,)
base += find(target,key)+len(key)
subStringMatchExact(target[find(target,key)+len(key):],key,matches,base)
else:
print matches
return matches
When I run the function, say for instance subStringMatchExact('abcdabcdababcdedakcdobcdabcd','abc'), the print matches line will have my interpreter print (0,4,10,24), which is correct. However the line return matches returns value None.
Similarly when I call print subStringMatchExact('abcdabcdababcdedakcdobcdabcd','abc'), the interpreter also gives None.
Can anyone help me correct this?
I rather think that you intended to return the recursive value on line 5. As it is, it just calls it and then continues to the end of the method, returning None. So, all you need is the insertion of the return keyword.
def subStringMatchExact(target,key,matches=(),base=0):
if find(target,key) != -1:
matches += (find(target,key)+base,)
base += find(target,key)+len(key)
return subStringMatchExact(target[find(target,key)+len(key):],key,matches,base)
else:
print matches
return matches
I think you mean for the statement at the end of the if clause to say:
return subStringMatchExact(...)
The return statement beneath your print statement is indeed working — it is successfully sending the answer back up the chain to the instance of the function that called it — but then the copy of the calling function is throwing it away. Without a return in the first clause of the if statement, a None gets returned instead.

Categories