My professor for my python class had this defined function in the lecture as an example of how to print out a string that would tell us if the first pixel of an image is more red, blue or green. My issue is that it does not output any value. This is word for word the code she put in the lecture slide but it does not do anything for me in Mu. What am I missing?
Below is the code:
def func3(img,x,y):
pixel=img[x][y]
r=pixel[0]
g=pixel[1]
b=pixel[2]
if r<30 and g>230 and b<30:
colourname='green'
elif r>200 and g<30 and b<30:
colourname='red'
else:
colourname='blue'
return colourname
Seems you have not understood functions properly.
Functions are a block of code which can be used multiple times.
functions run some code and return a result, like in your function, it is returning colorname
Now to get the output from a function, the first thing we have to do is call it.
So after defining the function;
def func3(img,x,y):
pixel=img[x][y]
r=pixel[0]
g=pixel[1]
b=pixel[2]
if r<30 and g>230 and b<30:
colourname='green'
elif r>200 and g<30 and b<30:
colourname='red'
else:
colourname='blue'
return colourname
# now i will call the function by simply writing its name with parenthesis in which we have to provide the parameters required by the function
func3(some_img, x, y) # some_img, x, y are the values of the parameters on which the code will act.
Now if you want to print the result on the console, use the print function;
print(func3(some_img, x, y))
Extra points to be noted as a beginner
return statement doesnot print anything on the console but is used to return a value from a function. What that means is, after the functions runs its code, at the end, it should be giving some value . Like in your example, you should be able to know at the end, which color it is. For that you return the colorname. print function is for printing the things to the console.
Related
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'
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.
Let me preface this by saying I am a total newbie to Python programming. Sorry to bother anyone with a possibly trivial question. But I am creating a program that calculates the user's BMI and displays their info along with their calculated BMI. I must create a function for the following:
1. BMI calculation
2. Retrieve user's weight
3. Retrieve user's height
4. Display user's weight, height, and calculated BMI
Here is my code:
BMI Calculator Code
These are my results:
Code Results
I'm supposed to show the calculated results too, but I'm doing one step at a time, making sure I can at least print the inputs first which is not happening. I'm so confused and don't know what to do to fix it. Any feedback is appreciated. Thanks.
use return
your input in function do not return any value to w, h, name in main code.
so, function need to be
def get_weight():
return int(input('message'))
return pass value to caller, now w can get value returned by get_weight function
w = get_weight()
Problem & Solution
You are getting the user input correctly, but you need to actually return the user input from the function for the value to accessible outside of the function. Currently in your code you are simply getting your user input, converting it to an integer, and immediately throwing away the values by letting them be garbage collected.
To return the value from the functions, use the return keyword:
def get_weight():
return int(input(...))
def get_height():
return int(input(...))
Improvements
Along with the solution above, there are some general improvements you can make to your code:
Follow PEP8. Put spaces between parameter, a newline at the end of the source file.
Use newline characters, rather than extra calls to print, for whitespace around displayed text. For example, use:
print('\nBMI calculator\n')
Rather than:
print()
print('BMI calculator')
print()
Is there any way to prevent a python function to return anything, even None? I would need an output like:
[...]
[...]
but I always get:
[...]
None
[...]
If requested, I can upload the source code as well, but it's a bit long.
Thanks in advance for any answer!
Nope. Just check with if output is None: and change the output accordingly.
Okay so looking at your code I assume you are printing the last line of code that generates the end results being "Goodbye! Total score: 9 points.".
What you need to do is instead of printing that line return it and print the function call like shown below.
Also functions always return something be it a string, a int or whatever type of data you set it to.
If you choose to not return anything it will always return None.
For if you are wondering what the \n is for it's to open up a new line because it seems like you want the space of a line between sessions of your game.
If not you can get rid of the \n it doesn't affect the outcome.
Anyway hope this helps!
def no_name():
# return the line of code that generates this outcome instead of printing it
#to get rid of the None.
return "Goodbye! Total score: 9 points.\n"
print no_name()
In Python an expression will always have to produce a result. Function calls are expressions, and are no exception here. As a result, any callable, including functions, produce a result, even if that result is None. From the documentation:
A call always returns some value, possibly None, unless it raises an exception.
You could just test for None:
result = functioncall()
if result is not None:
# ...
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