Function returns as error (python 3) - python

I am kinda new to Python, and I would like to ask a question :
def spam(a):
a = 1 + a
return a
spam(21)
print(spam)
input()
After running it, the output is function spam at 0x021B24F8. Shouldn't the output be 22? Any help will be appreciated.

The problem is that your function, i.e. spam is returning a value. You need to accept the value returned by the function and store it in a different variable as in
s = spam(21)
print(s)
Here, you will store the returning value in the variable s which you will print it out.
After making the correction, the program will print as expected as in
22
Note - As mentioned, having a single statement print(spam(21)) also works as spam(21) will return 22 to the print function which will then print out the value for you!

Related

Why is the function printing the first two lines before calling it?

Very new to python and I'm learning about defining and calling functions.
When def function4(x): and then define its output as a variable m, it prints the first two lines of the function before I even call it. Then when I call the function it only displays the return value. I was under the impression that anything indented under def function4(x): would not be executed unless function4(x) was specifically called?
Example:
def function4(x):
print(x)
print("still in this function")
return 3*x
m = function4(5)
print("BREAK")
print(m)
Output:
5
still in this function
BREAK
15
Process finished with exit code 0
Thanks for your time!
You're right, the function will not execute until you call it. You are calling it, though, right here:
m = function4(5)
So your print statements are executing in exactly the right place. You are setting m to the value returned by function4(5).
print does not call anything. It simply prints the string representation of whatever you give it to the console:
# a simple function to demonstrate
def f(x):
print("I am ", x)
return x
# I have not called f yet
print('Hello! ')
# I have printed the *function* f, but I still have not called it
# note the lack of parentheses
print('Here is a function: ', f)
print('We will call it now!')
# *Now* I am calling the function, as noted by the parentheses
x = f(1)
print('I have returned a value to x: ', x)
Which will do the following:
Hello!
Here is a function: <function f at 0x7fa958141840>
We will call it now!
I am 1
I have returned a value to x: 1
First of all I strongly recommend you that you use http://pythontutor.com/javascript.html#mode=edit if you want to know how your code is working, is very useful if you are new on Python.
Then, as for your code, you are calling the function when you declare the m variable, so that's the reason why the two print statements appear first.
The return value will only appear if you print the function, that's why the number 15 appears after all because you've printed it when you wrote print(m).
Hope this can help you, Goobye then and goodluck!.

Return statement in python function not returning anything [duplicate]

This question already has answers here:
Python: Return possibly not returning value
(5 answers)
Closed 3 years ago.
I don't understand the difference between return and print. I was told that you should use return in function statements but it doesn't return anything, so I've been using print in my functions. But I want to understand why return statements in my functions do not work.
def triangle_area(b, h):
return 0.5 * b * h
triangle_area(20, 10)
I would expect this return the multiplication, but it doesn't yield anything. Please help! And when I replace the return with print, it works perfectly. Am i supposed to use print in functions?
return and print are two very different instructions. Return has the purpose of storing the value that is computed by a function, value that will be used according to the programmer's wish. Print does what it says: it prints whatever you tell him to print.
Using return won't print anything, because this instruction is not built for such a purpose. Only for storing. Nothing more, nothing less. print displays something on the screen.
Like this:
print(triangle_area(20, 10))
Good luck to you all, bro!
It does return the product; what it doesn't do is print it (since you didn't tell it to).
Because you are not printing the return result from the function. Please try:
print(traingle_area(20,30))
You are not receiving the output the function is returning.
print(triangle_area(20, 10))
This will show the result.
It is returning the value, you simply are not capturing it or doing anything with it. For instance:
def triangle_area(b, h):
return 0.5 * b * h
output = triangle_area(20, 10) # capture return value
print(output)
Or as others have suggested, just pass the result straight to the print function if that's what you're looking to do:
def triangle_area(b, h):
return 0.5 * b * h
print(triangle_area(20, 10)) # capture return value and immediately pass to print function
Note that the output will be lost if passed straight to print(). If you want to use it later in your program, the first code block is more appropriate
Functions return a value, so you need to store them in variable.
print(triangle_area(20, 10))

Printing return value in function, Python

When I print the value that my function returns, it has strange characters.
If I print the value that I care inside the function, I obtain the right value: 0.653594771242
If I print the value that the function returns, I obtain:
function alpha at 0x05870630
def alpha(v1,v2):
a=(v1,v2)
b=1/sum(a)
print(b)
return b
alpha(0.817,0.713)
print(alpha)
This is because you are printing an object i.e a function. Functions in python are objects.
If you want to print the value returned by the function then this may help you.
print(alpha(0.817,0.713))
This way would probably make more sense to you.
def alpha(v1,v2):
a=(v1,v2)
b=1/sum(a)
print(b)
return b
result = alpha(0.817,0.713)
print(result)
This way the function is returning the value to result then you are simply printing the result.
Instead of print(alpha) you need to write
print(alpha(0.817,0.713))

Do you change variables AFTER you run a function in python?

So I wrote this function from a book I am reading, and this is how it starts:
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
ok, makes sense. and then, this is when this function is run where I got a little confused and wanted to confirm something:
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
the thing that confused me here is that the amount_of_cheese and amount_of_crackers is changing the variables (verbage? not sure if i am saying the right lingo) from cheese_count and boxes_of_crackers repectively from the first inital variable labels in the function.
so my question is, when you are using a different variable from the one that is used in the initial function you wrote, why would you change the name of the AFTER you wrote out the new variable names? how would the program know what the new variables are if it is shown after it?
i thought python reads programs top to bottom, or does it do it bottom to top?
does that make sense? i'm not sure how to explain it. thank you for any help. :)
(python 2.7)
I think you are just a bit confused on the naming rules for parameter passing.
Consider:
def foo(a, b):
print a
print b
and you can call foo as follows:
x = 1
y = 2
foo(x, y)
and you'll see:
1
2
The variable names of the arguments (a, b) in the function signature (1st line of function definition) do not have to agree with the actual variable names used when you invoke the function.
Think of it as this, when you call:
foo(x, y)
It's saying: "invoke the function foo; pass x in as a, pass y in as b". Furthermore, the arguments here are passed in as copies, so if you were to modify them inside the function, it won't change the values outside of the function, from where it was invoked. Consider the following:
def bar(a, b):
a = a + 1
b = b + 2
print a
x = 0
y = 0
bar(x, y)
print x
print y
and you'll see:
1
2
0
0
The script runs from top to bottom. The function executes when you call it, not when you define it.
I'd suggest trying to understand concepts like variables and function argument passing first.
def change(variable):
print variable
var1 = 1
change(var1)
In the above example, var1 is a variable in the main thread of execution.
When you call a function like change(), the scope changes. Variables you declared outside that function cease to exist so long as you're still in the function's scope. However, if you pass it an argument, such as var1, then you can use that value inside your function, by the name you give it in the function declaration: in this case, variable. But it is entirely separate from var! The value is the same, but it is a different variable!
Your question relates to function parameter transfer.
There are two types of parameter transfer into a function:
By value ------- value changed in function domain but not global domain
By reference ------- value changed in global domain
In python, non-atomic types are transferred by reference; atomic types (like string, integer) is transferred by value.
For example,
Case 1:
x = 20
def foo(x):
x+=10
foo()
print x // 20, rather than 30
Case 2:
d = {}
def foo(x): x['key']=20
foo(d)
print d // {'key': 20}

What is the formal difference between "print" and "return"? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 7 years ago.
Lets say I define a simple function which will display an integer passed to it:
def funct1(param1):
print(param1)
return(param1)
the output will be the same but and I know that when a return statement is used in a function the output can be used again. Otherwise the value of a print statement cannot be used. But I know this is not the formal definition, Can anyone provide me with a good definition?
Dramatically different things. Imagine if I have this python program:
#!/usr/bin/env python
def printAndReturnNothing():
x = "hello"
print(x)
def printAndReturn():
x = "hello"
print(x)
return x
def main():
ret = printAndReturn()
other = printAndReturnNothing()
print("ret is: %s" % ret)
print("other is: %s" % other)
if __name__ == "__main__":
main()
What do you expect to be the output?
hello
hello
ret is : hello
other is: None
Why?
Why? Because print takes its arguments/expressions and dumps them to standard output, so in the functions I made up, print will output the value of x, which is hello.
printAndReturn will return x to the caller of the method, so:
ret = printAndReturn()
ret will have the same value as x, i.e. "hello"
printAndReturnNothing doesn't return anything, so:
other = printAndReturnNothing()
other actually becomes None because that is the default return from a python function. Python functions always return something, but if no return is declared, the function will return None.
Resources
Going through the python tutorial will introduce you to these concepts: http://docs.python.org/tutorial
Here's something about functions form python's tutorial: http://docs.python.org/tutorial/controlflow.html#defining-functions
This example, as usual, demonstrates some new Python features:
The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.
With print() you will display to standard output the value of param1, while with return you will send param1 to the caller.
The two statements have a very different meaning, and you should not see the same behaviour. Post your whole program and it'll be easier to point out the difference to you.
Edit: as pointed by others, if you are in an interactive python shell you see the same effect (the value is printed), but that happens because the shell evaluates expressions and prints their output.
In this case, a function with a return statement is evaluated as the parameter of return itself, so the return value is echoed back. Don't let the interactive shell fool you! :)
Simple example to show the difference:
def foo():
print (5)
def bar():
return 7
x = foo()
y = bar()
print (x)
# will show "None" because foo() does not return a value
print (y)
# will show "7" because "7" was output from the bar() function by the return statement.
I'll start with a basic explanation. print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.
On a more expansive note, print will not in any way affect a function. It is simply there for the human user's benefit. It is very useful for understanding how a program works and can be used in debugging to check various values in a program without interrupting the program.
return is the main way that a function returns a value. All functions will return a value, and if there is no return statement (or yield but don't worry about that yet), it will return None. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user.
Consider these two programs:
def function_that_prints():
print "I printed"
def function_that_returns():
return "I returned"
f1 = function_that_prints()
f2 = function_that_returns()
print "Now let us see what the values of f1 and f2 are"
print f1
print f2
print (or print() if you're using Python 3) does exactly that—print anything that follows the keyword. It will also do nice things like automatically join multiple values with a space:
print 1, '2', 'three'
# 1 2 three
Otherwise print (print()) will do nothing from your program's point of view. It will not affect the control flow in any way and execution will resume with the very next instruction in your code block:
def foo():
print 'hello'
print 'again'
print 'and again'
On the other hand return (not return()) is designed to immediately break the control flow and exit the current function and return a specified value to the caller that called your function. It will always do this and just this. return itself will not cause anything to get printed to the screen. Even if you don't specify a return value an implicit None will get returned. If you skip a return altogether, an implicit return None will still happen at the end of your function:
def foo(y):
print 'hello'
return y + 1
print 'this place in code will never get reached :('
print foo(5)
# hello
# 6
def bar():
return # implicit return None
print bar() is None
# True
def baz(y):
x = y * 2
# implicit return None
z = baz()
print z is None
# True
The reason you see returned values printed to the screen is because you are probably working in the interactive Python shell that automatically prints any result for your own convenience.
The output is only the same in the interactive terminal. When you execute your program normally the results will be completely different.
I would suggest you to read a book about Python or read a tutorial that teaches you the basics, because this is a very basic thing.

Categories

Resources