Could someone please help me understand why the following function does not print out the reverse of the string? What am I doing wrong?
def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
return data[index]
print( data[index] )
myReverse('blahblah')
When you make a return call within the function, the control comes back to parent (which executed the function) ignoring the code within the scope of function after return. In your case, that is why print is not getting executed by your code.
Move the line containing print before return and move return to outside of the for loop. Your code should work then.
Suggestion:
There is simpler way to reverse the string using ::-1. For example:
>>> my_string = 'HELLO'
>>> my_string[::-1]
'OLLEH'
Intro: the execution of a for loop will stop once a return statement or break statement is encountered or there is an exception.
You have a return statement which makes the for loop stop (returning control to the caller) as soon as the statement is encountered in the first iteration.
Move the return statement outside the for loop
You are returning before print. So the line print( data[index] ) is never get executed.
Below code wil work just fine.
def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
print( data[index] , end = '')
Notice that this is a python3 solution. print in Python2 doesn't work like that.
So, get the same effect in python2 , first import the print from __future__.
from __future__ import print_function
And then, same as above.
Related
I'm unable to figure out how return works. In the following code, the first two pieces of code work just fine, but it fails to return any output at all when using return in a loop(#3).
# 1
def test(x):
return 'Testing'*x
test(3)
#2
def tst():
return 'Testing'
tst()
#3
for i in range(2):
tst()
The third one works, what's happening is that you don't do anything with the output because it's in a for loop.
We can see the results if we would print out the value returned from tst() function, i.e:
def tst():
return 'Testing'
for i in range(2):
print(tst())
And the output of the program will be:
Testing
Testing
The first 2 function calls in your code work because python just prints the value of the last line you called, but because it's in a for loop, it wouldn't.
The python REPL is not equivalent to the actual python interpreter. In the REPL/IDLE, the last expression evaluated implicitly prints. When you have a for loop, the REPL does not implicitly print the last expression, which is why you think that nothing's happening. You can see that's not the case if you explicitly print everything:
print(test(3)) # prints "TestingTestingTesting"
print(tst()) # prints "Testing"
for i in range(2):
print(tst) # prints "Testing" twice
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.
def testfunction():
for i in range(10):
return('a')
print(testfunction())
I want 'a' outputed 10 times in one line. If I use print instead of return, it gives me 10 'a's but each on a new line. Can you help?
return terminates the current function, while print is a call to another function(atleast in python 3)
Any code after a return statement will not be run.
Python's way of printing 10 a's would be:
print('a' * 10)
In your case it would look like the following:
def testfunction ():
return 'a' * 10
print(testfunction ())
The reason its only printing once is because the return statment finishes the function (the return function stops the loop).
In order to print 'a' 10 times you want to do the following:
def testfunction():
for i in range(10):
print('a')
testfunction()
If you want "a" printed 10 times in one single line then you can simply go for:
def TestCode():
print("a"*10)
There's no need to use the for loop. For loop will just "a" for 10 times but every time it'll be a new line.
You can also take in a function argument and get "a" printed as many times as desired.
Such as:
def TestCode(times):
t = "a"*times
print(t)
Test:
TestCode(5)
>>> aaaaa
TestCode(7)
>>> aaaaaaa
print and return get mixed up when starting Python.
A function can return anything but it doesn't mean that the value will be printed for you to see. A function can even return another function (it's called functional programming).
The function below is adapted from your question and it returns a string object. When you call the function, it returns the string object into the variable called x. That contains all of the info you wanted and you can print that to the console.
You could have also used yield or print in your for loop but that may be outside of the scope.
def test_function(item:str="a", n:int=10):
line = item*n # this will be a string object
return line
ten_a_letters = test_function()
print(ten_a_letters)
"aaaaaaaaaa"
two_b_letters = test_function("b",2)
print(two_b_letters)
"bb"
I want 'a' outputed 10 times in one line. If I use print instead of
return, it gives me 10 'a's but each on a new line.
If you want to use print, the you need to pass a 2nd parameter as follows:
def testfunction():
for i in range(10):
print('a', end='')
However, I think the pythonic way would be to do the following:
def testfunction():
print('a' * 10)
When you use return you end the execution of the function immediately and only one value is returned.
Other answers here provide an easier way to solve your problem (which is great), but I would like to suggest a different approach using yield (instead of return) and create a generator (which might be an overkill but a valid alternative nonetheless):
def testfunction():
for i in range(10):
yield('a')
print(''.join(x for x in testfunction()))
1. What does "yield" keyword do?
def test ():
print('a' * 10)
test()
Output will be 'aaaaaaaaaa'.
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
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.