Calling same function within itself changes argument value unexpectedly - python

Need some help in understanding why this function return the 'url_path_list' argument when called from within the same function?
When the script hits the part:
if count==1:
download_loop(url_path_list,count)
I do not ask the function to return anything yet, the new 'url_path_list' value seems to be returned. The url_path_list argument is returned as 009 for some reason without me asking it to (i think). I have a workaround for this, I just wanted to understand why the code is doing this.
import re
def download_loop(url_path_list,count):
sequence_num=re.findall('[0-9]+',url_path_list[count+1])[0]
num=sequence_num
while int(num)<10:
new_path=url_path_list[count+1][:3]+num+url_path_list[count+1][3+2:]
url_path_list[count+1]=new_path
print(url_path_list[2],count)
count+=1
if count==1:
download_loop(url_path_list,count)
count-=1
print(url_path_list[2],count)
num=int(num)
num+=1
num='0'*(len(sequence_num)-len(str(num))) + str(num)
download_loop(['Hello','thi01s','iii01s','a','test'],0)
EDIT: Just to clarify, my question is why the two print statements print different values when i think they should be the same.

Related

What is the use of a return statement? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 years ago.
Let me clarify; Let us say that you have 2 functions in Python:
def helloNot():
a = print("Heya!")
helloNot()
Which will print out Heya! without a return statement.
But if we use a return statement in this function:
def hello():
a = print("Heya!")
return a
hello()
This will print out Heya! as well.
I have read and learned that a return statement returns the result back to the function but
doesn't the result get automatically returned by whatever result you have without a return statement inside a function?
In our case let's use the function helloNot() (our function without the return statement):
our variable a, which is a print statement returns the result to the function when we call it or am I missing something?
On a side note,
Why and when would we use return statements?
Is it a good habit to start using return statements?
Are there a lot more advantages to using return statements than there are disadvantages?
EDIT:
using the print statement was an example to better present my question. My question does NOT revolve around the print statement.
Thank you.
Normally, when you call a function, you want to get some result. For example, when I write s = sorted([3,2,1]), that call to sorted returns [1,2,3]. If it didn't, there wouldn't be any reason for me to ever call it.
A return statement is the way a function provides that result. There's no other way to do that, so it's not a matter of style; if your function has a useful result, you need a return statement.
In some cases, you're only calling a function for its side-effects, and there is no useful result. That's the case with print.
In Python, a function always has to have a value, even if there's nothing useful, but None is a general-purpose "no useful value" value, and leaving off a return statement means you automatically return None.
So, if your function has nothing useful to return, leave off a return statement. You could explicitly return None, but don't do that—use that when you want the reader to know you're specifically returning None as a useful value (e.g., if your function returns None on Tuesday, 3 on Friday, and 'Hello' every other day, it should use return None on Tuesdays, not nothing). When you're writing a "procedure", a function that's called only for side-effects and has no value, just don't return.
Now, let's look at your two examples:
def helloNot():
a = print("Heya!")
This prints out Heya!, and assigns the return value of print to a local variable, which you never use, then falls off the end of the function and implicitly returns None.
def hello():
a = print("Heya!")
return a
This prints out Heya!, and assigns the return value of print to a local variable, and then returns that local variable.
As it happens, print always returns None, so either way, you happen to be returning None. hello is probably a little clearer: it tells the reader that we're returning the (possibly useless) return value of print.
But a better way to write this function is:
def hi():
print("Heya!")
After all, we know that print never has anything useful to return. Even if you didn't know that, you know that you didn't have a use for whatever it might return. So, why store it, and why return it?
You should use return statements if you want to compute a value from a function and give it back to the caller.
For your example, if the goal of the function is just to print a fixed string, there's no good reason to return the return value of print.
If you don't return anything from a function, Python implicitly returns a None. print falls in this category.
In [804]: a = print('something')
something
In [806]: print(a)
None
Similarly with functions that the user defines
In [807]: def f():
...: print('this is f')
...:
In [808]: fa = f() # Note this is assigning the *return value* of f()
this is f
In [809]: print(fa)
None
What you are doing does not require a return statement, you're right but consider you want to calculate an average.
def calculateAverage(x, y, z):
avg = ((x + y + z)/3)
return avg
Now that you have declared a function that has the ability to take 3 variables and return the calculated average you can now call it from any function and not have to have bulky code.
a = calculateAverage(7, 5, 9)
print("Average is:" + a)
Which will print to screen "Average is: 7"
The power of functions and return values is that you are able to make your code more readable by means of placing a single call to a sophisticated function in your main logic, which means you now have less lines of code and it is more legible/maintainable in the longrun.
Hopefully this helps.

How can i print and return a value from a function in python?

i cant figure out how to make a return value from a function return and print,
Example
def exe(a,b):
if a == b:
return 1
How would i get that 1 to print as well as return? Thanks in advance. I know its a stupid question and pretty useless, but im pretty sure it can be done and not knowing how is driving me nuts.
You can have multiple statements, but the "return" ends the function.
Print is just a statement when combined with the expressions (the stuff to the right of it) (in Python 2) that sends to expressions to standard out, (stdout), typically the console. In Python 3, print is a function, and so it's preferable to use print as a function in modern Python.
So you want print to come before return.
def exe(a,b):
if a == b:
print(1)
return 1
Check this code
def exe(a,b):
return 1 if a == b else None
print exe(1,1)

How do I perform some operation on the output of a function in Python?

I am trying to make a function's output behave as if it's my input. The goal is to make a new output from the old output.
I have some code that looks like this:
def func():
BLOCK OF CODE
func()
There is no return statement in the function and no parameters within the parenthesis.
When I type func() to call my function as shown above, I get the desired output, which is a bunch of printed statements. Now I want to do something with that output to get another output.
All I'm trying to do is effectively "pipe" the output of one function into the input of another function (or, if possible, not even worry about creating another function at all, and instead doing something more direct). I looked into Python 3 writing to a pipe
but it did not help me. I also tried defining another function and using the preceding function as a parameter, which did not work either:
def another_func(func):
print another_statement
another_func(func)
I also tried making a closure (which "kind" of worked because at least it printed the same thing that func() would print, but still not very encouraging):
def func():
def another_func():
print another_statement
BLOCK OF CODE
another_func()
Finally, I tried designing both a decorator and a nested function to accomplish this, but I have no parameters in my function, which really threw off my code (didn't print anything at all).
Any advice on how to manipulate a function's output like as if it is your input so that it's possible to create a new output?
You could achieve this by redirecting stdout using a decorator:
from StringIO import StringIO
import sys
def pipe(f):
def decorated(*args, **kwargs):
old,sys.stdout = sys.stdout,StringIO()
try:
result = f(*args, **kwargs)
output = sys.stdout.getvalue()
finally:
sys.stdout = old
return result, output
return decorated
You could then get the result, output pair from any decorated function, eg:
#pipe
def test(x):
print x
return 0
test(3) -> (0, '3\n')
However, I can't think of a good reason why you'd want to do this.
(Actually, that's not quite true; it is handy when writing unit tests for user IO, such as when testing student assignments in a software engineering course. I seriously doubt that that's what the OP is trying to do, though.)
Return the desired value(s) from the function - instead of printing the values on the console, return them as strings, numbers, lists or any other type that makes sense. Otherwise, how do you expect to "connect" the output of a function as the input to another, if there is no output to begin with?
Of course, printing on the console doesn't count as output unless you're planning to eventually use OS pipes or a similar mechanism to connect two programs on the console, but keep things simple! just use the function's return values and worry about pipes later if and only if that's necessary for your problem in particular.
After reading the comments: "connecting" two functions by printing on the console from one and reading from the console from the other would be a really bad idea in this case, first you have to grasp the way functions return values to each other, trust me on this one: you have to rethink your program! even though other answers (strictly speaking) answer your original question, that's absolutely not what you should do.
just for fun ... because OP asked for it
import StringIO
import sys
def func1():
for i in range(1,10):
print "some stuff %d"%i
def func2(func):
old_std = sys.stdout
sys.stdout = StringIO.StringIO()
try:
func()
return sys.stdout.getvalue().splitlines()
finally:
sys.stdout = old_std
print func2(func1)
You need to return a value from your function. This can be used to assign the value into another variable.
Say I define some function doubleThis that will double the input
def doubleThis(x):
print 'this is x :', x
return x * 2 # note the return keyword
Now I can call the function with 3, and it returns 6 as expected
>>> doubleThis(3)
this is x : 3
6
Now I have another function subtractOne that returns the input value, minus 1.
def subtractOne(i):
print 'this is i :', i
return i - 1
Now comes the answer to your question. Note that we can call the first function as the input to the second, due to the fact that it has a return value.
>>> subtractOne(doubleThis(3))
this is x : 3
this is i : 6
5

Read the value returned by a function without updating it?

I have some code that will update and return a value every fifteen seconds.
def set_interval(func, sec):
def func_wrapper():
set_interval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start()
return t
def gem_price():
return random.randint(1,1000)
print ("Updated")
set_interval(gem_price, 15)
Later within the code, I want to output the value that was returned by the function 'gem_price'. The way I've been going about this is by printing the function itself.
print(gem_price())
The problem I have is, everytime I output the 'gem_price' using this method, it will update the value. I would like to able to output the value without having to update it.
Is there any way to do this? Thanks in advance!
If you want to print value after every 15 sec, you can use this:
import time
while True:
...
Yourcode
...
print('The answer is....', answer)
time.sleep(15)
gem_price() just returns a random integer between 1 and 1000 every time it is called. It does not store anything.
If you want to store this value, just assign it to a variable: value = gem_price() and then use this variable and not the function (unless you want another value, but to keep it you should assign it to another var).
It seems you don't completely understand how functions work, by the way. A variable inside of a function gets deleted when the function exits (generally). Also, the execution flow stops after the return statement, so your print is never reached and thus never executed.
You should read this part of the Python tutorial. Actually, all of it.

What is the type of parameter, and what does this function do?

I am having trouble with the code below:
def myprogram(x):
if x == []:
return x
else:
return myprogram(x[1:]) + [ x[0] ]
What is the parameter type (x)?
What does this function do?
I'm supposed to write code that calls this function with a parameter and find the return value, but i can't do that without understanding what is going on here. any help/feedback would be appreciated.
Since this is clearly homework, I'll limit my answer to a hint.
I'm supposed to write code that calls this function
It is clear that the function is expecting a list. I leave it to you to figure out the rest.
If you are unsure how to proceed, you could try to call it with various lists to see what it returns. However, ultimately you will have to read and understand the source code to be certain about what the function does.
That is a recursive function, it continues calling itself until the termination condition stops it
For example, if you run this code:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n -1)
what would you expect would return if you invoke with factorial(5)?
Another post on how to make them here: How can I build a recursive function in python?

Categories

Resources