recursive function paradox in Python.. how can it be explained? - python

I made a very simple function that takes a list of numbers and returns a list of numbers rounded by some digits:
def rounded(lista, digits = 3):
neulist = []
for i in lista:
neulist.append(round(i, digits))
return neulist
However, I mistakenly put the function itself in the code instead of the built-in round() (as in the example below):
def rounded(lista, digits = 3):
neulist = []
for i in lista:
neulist.append(rounded(i, digits))
return neulist
and got this output:
Traceback (most recent call last):
File "<pyshell#286>", line 1, in <module>
rounded(a)
File "<pyshell#284>", line 4, in rounded
neulist.append(rounded(i, digits))
File "<pyshell#284>", line 3, in rounded
for i in lista:
TypeError: 'float' object is not iterable
The question is: how does the interpreter know that it had to apply the function rounded() while evaluating the function rounded() itself? How can it anyway now that rounded() is a function taking floats if it is attempting to interpret that very function? Is there a sort of two cycle procedure to evaluate & interpret functions? Or am I getting something wrong here?

The function is an object. It is created at definition, not when it is called, so if Python didn't know how to use it, it would've raised an error before any calling was done.
However, you called it with a list. During the iteration, the function is called recursively with the first item of the list - presumably, a float. With this float as argument, for i in lista: doesn't make sense anymore, and you have the error.

You've just stumbled upon recursion.
Recursive functions are very common in programming. Consider the following (naive) function for calculating the nth fibbonacci number:
def fib(x):
if x<=2:
return 1
else:
return fib(x-1)+fib(x-2)
The function knows that it calls itself, because the function definition is noted as soon as the interpreter reaches fib(x):. From that point on, fib is defined. For python in particular, since it's a dynamically typed language, there's no difference if you call the function with a integer, a string or a float - all it matters is that the function takes exactly one argument.

There are indeed two processes occurring here. The function is compiled as it's encountered in the source text, then a call is made to it afterward. The body of the function includes a call to rounded, but that's actually kept track of as the name of the function. Check this out:
def fun1(x):
if x == 0:
print x
else:
fun1(x-1)
fun2 = fun1
def fun1(x):
print x
fun2(3)
Here we're defining fun1() with an apparently recursive call to itself. However, after redefining fun1(), the call in the first definition of the function now refers to a different function entirely.

Related

Having a hard time understanding nested functions

python newbie here, I'm currently learning about nested functions in python. I'm having a particularly hard time understanding code from the example below. Particularly, at the bottom of the script, when you print echo(2)("hello") - how does the inner_function know to take that string "hello" as its argument input? in my head, I'd think you would have to pass the string as some sort of input to the outer function (echo)? Simply placing the string in brackets adjacent to the call of the outer function just somehow works? I can't seem to wrap my head around this..
-aspiring pythonista
# Define echo
def echo(n):
"""Return the inner_echo function."""
# Define inner_echo
def inner_echo(word1):
"""Concatenate n copies of word1."""
echo_word = word1 * n
return echo_word
# Return inner_echo
return inner_echo
# Call twice() and thrice() then print
print(echo(2)('hello'), echo(3)('hello'))
The important thing here is that in Python, functions themselves are objects, too. Functions can return any type of object, so functions can in principle also return functions. And this is what echo does.
So, the output of your function call echo(2) is again a function and echo(2)("hello") evaluates that function - with "hello" as an input argument.
Maybe it is easier to understand that concept if you would split that call into two lines:
my_function_object = echo(2) # creates a new function
my_function_object("hello") # call that new function
EDIT
Perhaps this makes it clearer: If you spell out a function name without the brackets you are dealing with the function as an object. For example,
x = numpy.sqrt(4) # x is a number
y = numpy.sqrt # y is a function object
z = y(4) # z is a number
Next, if you look at the statement return echo_word in the echo function, you will notice that what is returned is the inner function (without any brackets). So it is a function object that is returned by echo. You can check that also with print(echo(2))

how can I fix list function in python [duplicate]

Given the following integers and calculation
from __future__ import division
a = 23
b = 45
c = 16
round((a/b)*0.9*c)
This results in:
TypeError: 'int' object is not callable.
How can I round the output to an integer?
Somewhere else in your code you have something that looks like this:
round = 42
Then when you write
round((a/b)*0.9*c)
that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.
The problem is whatever code binds an int to the name round. Find that and remove it.
I got the same error (TypeError: 'int' object is not callable)
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
return xl
... ... ... ...
>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable
after reading this post I realized that I forgot a multiplication sign * so
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
return xl
xlim(1.0,100.0,0.0,0.0)
0.005
tanks
Stop stomping on round somewhere else by binding an int to it.
I was also facing this issue but in a little different scenario.
Scenario:
param = 1
def param():
.....
def func():
if param:
var = {passing a dict here}
param(var)
It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.
Changed function name to something else and it worked.
So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code.
So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.
I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.
In my case I changed:
return <variable>
with:
return str(<variable>)
try with the following and it must work:
str(round((a/b)*0.9*c))
Sometimes the problem would be forgetting an operator while calculation.
Example:
print(n-(-1+(math.sqrt(1-4(2*(-n))))/2)) rather
it has to be
print(n-(-1+(math.sqrt(1-4*(2*(-n))))/2))
HTH
There are two reasons for this error "TypeError: 'int' object is not callable"
Function Has an Integer Value
Consider
a = [5, 10, 15, 20]
max = 0
max = max(a)
print(max)
This will produce TypeError: 'int' object is not callable.
Just change the variable name "max" to var(say).
a = [5, 10, 15, 20]
var = 0
var = max(a)
print(var)
The above code will run perfectly without any error!!
Missing a Mathematical Operator
Consider
a = 5
b = a(a+1)
print(b)
This will also produce TypeError: 'int' object is not callable.
You might have forgotten to put the operator in between ( '*' in this case )
As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.
You can always use the below method to disambiguate the function.
__import__('__builtin__').round((a/b)*0.9*c)
__builtin__ is the module name for all the built in functions like round, min, max etc. Use the appropriate module name for functions from other modules.
I encountered this error because I was calling a function inside my model that used the #property decorator.
#property
def volume_range(self):
return self.max_oz - self.min_oz
When I tried to call this method in my serializer, I hit the error "TypeError: 'int' object is not callable".
def get_oz_range(self, obj):
return obj.volume_range()
In short, the issue was that the #property decorator turns a function into a getter. You can read more about property() in this SO response.
The solution for me was to access volume_range like a variable and not call it as a function:
def get_oz_range(self, obj):
return obj.volume_range # No more parenthesis

When is a function called/referred to and when is it being executed?

I'm relatively new to Python and I have a (I guess) pretty basic question on functions in Python.
I'm rewatching basics tutorials in order to really understand more of the structures and not just use them. I used some basic code from a tutorial and tried different simple variations and I don't fully understand the outcomes and when a function is being referred to, i.e. when its return value is being called for, and when it's being executed.
x=6
def example():
globx = x
print(globx)
globx+=5
print(globx)
example()
This defines the function and afterwards calls for it to be executed and as it's being executed it prints 6 and then prints 11, as expected.
Now:
x=6
def example():
globx = x
print(globx)
globx+=5
print(globx)
print(example())
I would have expected this to print "None" since print is looking for a return value of the function to print it but example() doesn't return a value. Instead 6, 11 and None are being printed. So I assume print(example()) calls for example()'s return value to print it but before also executes the function. (Please correct me if I got that wrong.).
Even when I'm just assigning the return value to a variable x = example() after the definition of the function, it will also execute the function and print 6 and then 11.
x=6
def example():
globx = x
print(globx)
globx+=5
print(globx)
x = example()
Is a function always being executed when it's written out? (Ecxcept in the def)
Is there a way to make use of a functions return value without it being fully executed?
For example if I had a more complex code and at some point I want to make use of a functions return value but don't want it to be run.
Thanks in advance!
What you say seems overall correct, even if it seems off what you expected.
Generally, you can see it as, when the function has parentheses at the end, i.e. example(), the function is executed.
Your last question is a bit vague, but you can stop executing the function at some point by using the return keyword inside the function. This makes sense in e.g. a function that performs some resource-intensive calculations, but occasionally there's a chance to take a shortcut.
As an example
def calculate_thing(shortcut = False):
if shortcut:
return 3
# Resource-intensive, time-consuming calculations go here
return result_of_calculations
Calling this function with calculate_thing(shortcut=True) will quickly return 3, because the function stops executing when we hit return 3. On the other hand, calling it by calculate_thing(shortcut=False) or calculate_thing() (False is the default value for shortcut) will make the function run for a while, doing some calculations, and then it returns whatever value was assigned to the variable result_of_calculations.
You are getting confused by what a function returns and what a function does.
In your case you have a function which has two print() statements. Those statements have nothing to do with the value that the function will return and will print their corresponding values on every invocation of the function example().
The return value of the function is defined using the return keyword and if it is not defined then it is None. Obviously the function needs to be executed in order to get it to return a value.
A function does something, it literally performs a function. If you want that function to show you results as it's doing its job, you can print() things. If you just want it to do its job and save the results for later, you return them to a variable that calls the function. You can do both!
def just_print(input):
print('Here is a function printing!', input)
just_print('cool!')
>> 'Here is a function printing!', 'cool!'
def return_value(input):
return 'Hello ' + input
# We can store the return for future use
save_return_val = return_value('Ari')
print(save_return_val)
>> 'Hello Ari'
# Just print it
print(return_value('Ari'))
>> 'Hello Ari'

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.

Python custom function

I have been working at learning Python over the last week and it has been going really well, however I have now been introduced to custom functions and I sort of hit a wall. While I understand the basics of it, such as:
def helloworld():
print("Hello World!")
helloworld()
I know this will print "Hello World!".
However, when it comes to getting information from one function to another, I find that confusing. ie: function1 and function2 have to work together to perform a task. Also, when to use the return command.
Lastly, when I have a list or a dictionary inside of a function. I'll make something up just as an example.
def my_function():
my_dict = {"Key1":Value1,
"Key2":Value2,
"Key3":Value3,
"Key4":Value4,}
How would I access the key/value and be able to change them from outside of the function? ie: If I had a program that let you input/output player stats or a character attributes in a video game.
I understand bits and pieces of this, it just confuses me when they have different functions calling on each other.
Also, since this was my first encounter with the custom functions. Is this really ambitious to pursue and this could be the reason for all of my confusion? Since this is the most complex program I have seen yet.
Functions in python can be both, a regular procedure and a function with a return value. Actually, every Python's function will return a value, which might be None.
If a return statement is not present, then your function will be executed completely and leave normally following the code flow, yielding None as a return value.
def foo():
pass
foo() == None
>>> True
If you have a return statement inside your function. The return value will be the return value of the expression following it. For example you may have return None and you'll be explicitly returning None. You can also have return without anything else and there you'll be implicitly returning None, or, you can have return 3 and you'll be returning value 3. This may grow in complexity.
def foo():
print('hello')
return
print('world')
foo()
>>>'hello'
def add(a,b):
return a + b
add(3,4)
>>>7
If you want a dictionary (or any object) you created inside a function, just return it:
def my_function():
my_dict = {"Key1":Value1,
"Key2":Value2,
"Key3":Value3,
"Key4":Value4,}
return my_dict
d = my_function()
d['Key1']
>>> Value1
Those are the basics of function calling. There's even more. There are functions that return functions (also treated as decorators. You can even return multiple values (not really, you'll be just returning a tuple) and a lot a fun stuff :)
def two_values():
return 3,4
a,b = two_values()
print(a)
>>>3
print(b)
>>>4
Hope this helps!
The primary way to pass information between functions is with arguments and return values. Functions can't see each other's variables. You might think that after
def my_function():
my_dict = {"Key1":Value1,
"Key2":Value2,
"Key3":Value3,
"Key4":Value4,}
my_function()
my_dict would have a value that other functions would be able to see, but it turns out that's a really brittle way to design a language. Every time you call my_function, my_dict would lose its old value, even if you were still using it. Also, you'd have to know all the names used by every function in the system when picking the names to use when writing a new function, and the whole thing would rapidly become unmanageable. Python doesn't work that way; I can't think of any languages that do.
Instead, if a function needs to make information available to its caller, return the thing its caller needs to see:
def my_function():
return {"Key1":"Value1",
"Key2":"Value2",
"Key3":"Value3",
"Key4":"Value4",}
print(my_function()['Key1']) # Prints Value1
Note that a function ends when its execution hits a return statement (even if it's in the middle of a loop); you can't execute one return now, one return later, keep going, and return two things when you hit the end of the function. If you want to do that, keep a list of things you want to return and return the list when you're done.
You send information into and out of functions with arguments and return values, respectively. This function, for example:
def square(number):
"""Return the square of a number."""
return number * number
... recieves information through the number argument, and sends information back with the return ... statement. You can use it like this:
>>> x = square(7)
>>> print(x)
49
As you can see, we passed the value 7 to the function, and it returned the value 49 (which we stored in the variable x).
Now, lets say we have another function:
def halve(number):
"""Return half of a number."""
return number / 2.0
We can send information between two functions in a couple of different ways.
Use a temporary variable:
>>> tmp = square(6)
>>> halve(tmp)
18.0
use the first function directly as an argument to the second:
>>> halve(square(8))
32.0
Which of those you use will depend partly on personal taste, and partly on how complicated the thing you're trying to do is.
Even though they have the same name, the number variables inside square() and halve() are completely separate from each other, and they're invisible outside those functions:
>>> number
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'number' is not defined
So, it's actually impossible to "see" the variable my_dict in your example function. What you would normally do is something like this:
def my_function(my_dict):
# do something with my_dict
return my_dict
... and define my_dict outside the function.
(It's actually a little bit more complicated than that - dict objects are mutable (which just means they can change), so often you don't actually need to return them. However, for the time being it's probably best to get used to returning everything, just to be safe).

Categories

Resources