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
Related
I have tested with both jupyter and python terminal, that when the codes reach return, it outputs the result, even if it true or false, but why it does not print the inner function results? Does python always print the return result?
def is_evern(i):
if i%2==0:
print(i,'is even')
return(True)
print(i,'is odd')
return(False)
def func_call(i):
return(True)
Output of the commands:
>>> is_evern(5)
5 is odd
False
>>> func_call(is_evern(5))
5 is odd
True
>>>
Python has three types of scopes:
1. Built-in
2. Global
3. Enclosed
4. Local
When you use the terminal, you are in Global scope, and it only has access to the first functions that you are calling. When you type the name of the function and call it, the terminal(python command line), is only seeing the immediate return, and it prints it, but has no access to the inner return, so you need to pass it to higher scope to be visible for the python.
When running commands interactively, Python prints the result of the expression you type. Additionally, it will print anything you output with print statements.
However, it does not print the result of every function you call. Just the last one.
When you have a function with a return statement, but you don't assign that return to an actual variable, it will print the returned value
x = func_call(is_evern(5))
>>5 is odd
returning to a variable will prevent the return from printing. Or just don't return a variable if you have no intention of using it
It didn't print the results because you didn't tell it to do so. return and print are very different commands.
Perhaps you're confused because of the expression evaluation inherent in many IDEs (interactive development environment). Python's interactive mode is one of these: if given an expression, rather than a command, the interpreter will print the expression's value; this is a feature of the IDE.
For instance, if you enter 2+3, the IDE will display 5. If you enter a = 2+3, the IDE will print nothing (but 5 gets assigned to a).
Now, let's walk through your IDE display:
>>> is_evern(5)
5 is odd this comes from your print command
False this is the result of the expression "is_evern(5)"
>>> func_call(is_evern(5))
5 is odd this comes from your print command
True this is the result of the expression
In this second statement, you don't get False because that's not the result of the whole expression. Instead, that value got assigned to i in func_call, used immediately.
"what happens" going step by step:
iseven(5)
5 is passed to function
in function:
evaluated i%2 which is 5%2 => 1
evaluated 1==0 => False (skipps if block)
print(i, 'is odd') outputs 5 is odd
returning False (btw, return doesn't need parentheses, only whitespace: return False)
False is now sort of in the place of iseven(5)
so >>> iseven(5) is equal to writing >>> False
pythons IDLE (and other IDEs) are built so that if after >>> there is something other than None (builtin object), it is printed out
check by typing
>>> False
False # expected output
>>> None
>>> # no output
main problem
func_call(is_evern(5))
iseven(5) is evaluated like in 1st paragraph and False is returned (note: evaluation requires printing 5 is odd)
and again False is in place of iseven(5)
so: func_call(is_evern(5)) equals to func_call(False)
now False is passed to func_call
inside of function:
i has value False
True is returned
>>> True is in place of >>> func_call(is_evern(5))
and, for reasons explained in last row 1st paragraph, True is printed
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'.
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.
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.
I just started learning Python and I've just been messing around typing different codes for practice to learn, and I made this code:
import math
def lol():
print (math.cos(math.pi))
print ("I hope this works")
def print_twice(bruce):
print bruce
print bruce
print_twice(lol())
When I run it, my output is:
-1.0
I hope this works
None
None
How come it isn't printing the function lol() twice?
Your code print_twice(lol()) is saying to execute lol() and pass it's return value into print_twice(). Since you didn't specify a return value for lol(), it returns None. So, lol() is printed once when it gets executed, and both print statements in print_twice() print passed value of None.
This is what you want:
def lol():
print (math.cos(math.pi))
print ("I hope this works")
def print_twice(bruce):
bruce()
bruce()
print_twice(lol)
Instead of passing the return value of lol(), we are now passing the function lol, which we then execute twice in print_twice().
You should note that printing is different from returning.
When you call print_twice(lol()) it will first call lol() which will print -1.0 and I hope this works and will return None, then it will continue calling print_twice(None) which will call print None twice.
How you might run as expected:
def lol():
print "lol"
def run_twice(func):
func()
func()
run_twice(lol)