If I use this
def myfunction():
print('asd')
print(myfunction)
The IDE tells me None
but if I use this
import math
print (math.cos(90))
The IDE tells me the COS90°
Why?
It's all about return value.
def myfun(x):
return x
print(myfun("hello")) will return hello.
Your function (myfunction) does not return a value, that's to say it returns None value. So, print (a built in python function) returns that value.
When functions are called they always return something they processes.
def myfunction():
print('asd')
This will print the output. Since there is nothing explicitly returned, the function by default return None
Now lets add a bit of complexity to your function:
def myfunction(text):
print(text * 2)
This will print the text it gets twice. And it works just fine. But lets say you need to store the "printed twice" text to a variable.
Try this:
def myfunction(text):
print(text * 2)
twoText = myFunction("some text foo")
print(twoText)
Output should look like this:
some text foosome text foo
None
This is happening because you are in your function first printing twice some text foo and then printing what your function returned. In this case it returned None since nothing was explicitly returned.
To fix this you just replace print with return.
def myfunction(text):
return text * 2
twoText = myFunction("some text foo")
print(twoText)
The output is correct because you print only the return of the function.
some text foosome text foo
The math function returnes data like this:
def cos(number):
# Insert super complex math calculation here
return result
If it didn't do this you would not be able to store the result in a variable, instead it would just be printed.
If a Question is general than there is no difference except built-in function is one that is properly tested and approved by author's command; You can contribute too if You write something good and useful - don't shy offer it to community; ppl will thank You.
But if You mean exactly Your example then You have to change code to be:
def myfunction():
print('asd')
myfunction()
this is the way to call function without arguments, You could have
def myfunction(n):
print(n)
myfunction('hi')
this would print hi and so on
Related
I'm using Spyder to create a web scraper, and things are moving smoothly so far. As a rookie, Spyder's Code Analysis function is something I find useful for improving the standard of my code. However, while I usually understand its instructions/recommendations, I've recently run into a bit of a blip. I'll post some sample code first:
def payments(): #### This is line 59 on the editor. Preceding it is another function with a a format similar to this one.
"""Obtains data on the weekly payments in the country"""
html = get(source["Payments"]).text
html = bs(html,"lxml")
location = "/home/oduduwa/Desktop/Python Projects/Financial Analyser/CBN Data/Payments.csv"
def file_check():
headings = [i.text for i in html.find_all(width="284")][:10]
headings.insert(0, "Date")
if isfile(location) is False:
with open(location,"w") as file_obj:
writer(file_obj).writerow(headings)
return
file_check()
file = open(location,"r").read()
dates = [i.text.strip()[8:] for i in html.find_all("th",colspan="2")]
values = [i.text.strip()[4:] for i in html.find_all(width="149") if i.text.strip()[4:]!=""]
values = array(values).reshape(int(len(values)/10),10)
values = insert(values,0,array(dates).transpose(),axis=1)[::-1]
for i in range(len(values)):
if values[i][0] not in file:
with open(location,"a+",newline=("\n")) as file_obj:
writer(file_obj).writerow(values[i])
return
The code runs fin and does everything it should. What I don't really understand, however, is Spyder's statement that there's a useless return call in the code block. Here's what it says specifically:
But from what I gather, every function call is necessary in this coding block. What could I have missed? Thanks for your time!
Python functions implicitly return None by default. The following function definitions are equivalent.
def foo():
pass
def foo():
return
def foo():
return None
In my opinion, it is good practice to either
have no return statement at all - this indicates that you are not supposed to assign a name to the return value when calling the function, or
explicitly return None, to indicate "no result" for a function that could return a meaningful value, or
use just return to make a function that returns no meaningful value stop execution.
Example for situation 1:
def switch_first_last_in_place(lst):
'switch the first and last elements of a list in-place'
lst[0], lst[-1] = lst[-1], lst[0]
This function implicitly returns None and you are not supposed to issue
result = switch_first_last_in_place([1, 2, 3])
Example for situation 2:
def get_user_info_from_database(username):
'fetches user info, returns None if user does not exist'
if user_exist(username):
return query_db(username)
else:
return None
This function explicitly returns None to indicate a user was not found. Assignments like
result = get_user_info_from_database('Bob')
are expected. The part
else:
return None
is unnecessary but I like being explicit in cases where None is a meaningful return value.
Example for situation 3:
def assert_exists(thing, *containers):
'raise AssertionError if thing cannot be found in any container'
for container in containers:
if thing in container:
return
raise AssertionError
Here, return is merely used to break out of the function.
I don't like the bare return at the end of the functions in your example. It is not used to end execution and those functions cannot return other values. I would remove it.
You've misunderstood. The warning isn't talking about any of the functions you are calling. It's referring to your use of the return keyword.
This function:
def print_hello():
print("Hello")
return
Is equivalent to this function:
def print_hello():
print("Hello")
return None
Which is equivalent to this function:
def print_hello():
print("Hello")
The warning is saying, that your return statements are useless, and are not required.
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'.
I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?
string = "Hello"
reverse = string[::-1]
print(reverse)
I tried putting it in a function but I cannot make it print Hello.
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
also tried this
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
Nothing seems to work. I'm having same problem with this as well.
total = 0
def length(words):
for i in words:
total += 1
return total
Functions without a return value
Functions that just take action or do something without returning a value (for example, print).
Functions that don't return a value can be defined like that:
def sayHello():
print "Hello!"
And can be used (called) like that:
sayHello()
And the output will be:
Hello!
Function parameters
A function can also receive parameters (type of variables) from the caller. It's better to demonstrate it with an example.
A function that receives a name and greets this name:
def sayHelloTo(name):
print "Hello", name
It can be called like that:
sayHelloTo("Yotam")
And the output will be:
Hello Yotam
The parameters are the function's input.
Functions with a return value
Other functions, unlike sayHello() or sayHelloTo(name) (that just do something) can return a value. For example, let's make a function that rolls a dice (returns a random number between 1 and 6).
from random import randint
def rollDice():
result = randint(1, 6)
return result
The return keyword just sets the output value of the function and exits the function. An example use of the rollDice function will be:
dice = rollDice()
print "The dice says", dice
When the function hits a return keyword, it finishes and the return value (in our case, the variable result) will be placed instead of the function call. Let's assume randint(1, 6) has produced the number 3.
Result becomes 3.
Result is returned.
Now, instead of the line:
dice = rollDice()
We can treat the line as:
dice = 3
(rollDice() was replaced with 3)
Functions with parameters and a return value
Some functions (for example, math functions) can take inputs AND produce outputs. For example, let's make a function that receives 2 numbers and outputs the greater one.
def max(a,b):
if a > b:
return a
else:
return b
What it does is pretty clear, isn't it? If a is greater, it returns the value of it. Otherwise, returns the value of b.
It can be used like that:
print max(4, 6)
And the output will be:
6
Now, your case
What you want to do is a function that reverses a string. It should take 1 parameter (input) - the string you want to reverse, and output 1 value - the reversed string. This can be accomplished like that:
def reverse_a_string(my_text):
return my_text[::-1]
now you can do something like that:
s = raw_input("Please enter a string to be reversed\n") #input in Python3
r = reverse_a_string(s)
print r
r will contain the reversed value of s, and will be printed.
About your second function - well, I assume that based on this answer you can make it yourself, but comment me if you need assistance with the second one.
Local variables
About your 3rd example:
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
This is something that is really worth delaying and understanding.
the variable reverse is first used inside the function. This makes it a local variable.
This means that the variable is stored in the memory when the function is called, and when it finishes, it is removed. You can say it's lifetime is from when the function is called to when the function is done.
This means that even if you called reverse_a_string(string), you wouln't be able to use the reverse variable outside of the function, because it would be local.
If you do want to pass a value like that, you have to "declare" your variable outside of the function and to use the global keyword, like that:
reverse = "" #This makes reverse a global variable
def reverse_a_string(string):
global reverse #Stating that we are going to use the global variable reverse
reverse = string[::-1]
# Then you can call it like that:
reverse_a_string("Hello")
print reverse
The output will be
olleH
Although it's strongly not recommended to do it in Python, or in any other language.
Once you create a function you must call it. You have created the function reverse_a_string but then you never actually call it. Think about a function as a button that does something everytime it is pushed (or in our case called). If you never push the button then although it has the potential to do something, it never will. In order for the set of instructions to happen we need to push the button (or in our case call the function). So in order for your code to work you first need to define the function then actually call it:
def reverse_a_string():
string="Hello"
reverse = string[::-1]
print reverse
reverse_a_string()
Result: 'olleH'
If you want to pass your own string in to the function so it doesn't just return 'olleH' all the time your code needs to look like such:
def reverse_a_string(stringThatWillBeReversed):
reverse = stringThatWillBeReversed[::-1]
print reverse
reverse_a_string('whateverStringYouWant')
Result: The reverse of the string you entered.
Hope that helps!
I don't know whether you are asking how to define functions in python or something else
If you want to learn python functions, go to http://www.tutorialspoint.com/python/python_functions.htm or just write python tutorial in google, you will get billions of good sites
def reverse_a_string(string):
#function definition
reverse = string[::-1]
print(reverse)
#function call
reverse_a_string("your string")
But you to define function for this, you could simply do
print( string[::-1] )
# defines the 'Reverse a String' function and its arguments
def reverse_a_string():
print(string)
reverse = string[::-1]
print(reverse)
print("Type a string") # asks the user for a string input
string = input() # assigns whatever the user input to the string variable
reverse_a_string() # simply calls the function
for functions, you have to define the function, then simply call it with the function name i.e. funtion()
In my example, I ask for a string, assign that to the variable, and use it within the function. If you just want to print hello (I'm a little unclear from your question) then simply including the print("hello") or w/ variable print(string) will work inside the function as well.
I know this is super basic and I have been searching everywhere but I am still very confused by everything I'm seeing and am not sure the best way to do this and am having a hard time wrapping my head around it.
I have a script where I have multiple functions. I would like the first function to pass it's output to the second, then the second pass it's output to the third, etc. Each does it's own step in an overall process to the starting dataset.
For example, very simplified with bad names but this is to just get the basic structure:
#!/usr/bin/python
# script called process.py
import sys
infile = sys.argv[1]
def function_one():
do things
return function_one_output
def function_two():
take output from function_one, and do more things
return function_two_output
def function_three():
take output from function_two, do more things
return/print function_three_output
I want this to run as one script and print the output/write to new file or whatever which I know how to do. Just am unclear on how to pass the intermediate outputs of each function to the next etc.
infile -> function_one -> (intermediate1) -> function_two -> (intermediate2) -> function_three -> final result/outfile
I know I need to use return, but I am unsure how to call this at the end to get my final output
Individually?
function_one(infile)
function_two()
function_three()
or within each other?
function_three(function_two(function_one(infile)))
or within the actual function?
def function_one():
do things
return function_one_output
def function_two():
input_for_this_function = function_one()
# etc etc etc
Thank you friends, I am over complicating this and need a very simple way to understand it.
You could define a data streaming helper function
from functools import reduce
def flow(seed, *funcs):
return reduce(lambda arg, func: func(arg), funcs, seed)
flow(infile, function_one, function_two, function_three)
#for example
flow('HELLO', str.lower, str.capitalize, str.swapcase)
#returns 'hELLO'
edit
I would now suggest that a more "pythonic" way to implement the flow function above is:
def flow(seed, *funcs):
for func in funcs:
seed = func(seed)
return seed;
As ZdaR mentioned, you can run each function and store the result in a variable then pass it to the next function.
def function_one(file):
do things on file
return function_one_output
def function_two(myData):
doThings on myData
return function_two_output
def function_three(moreData):
doMoreThings on moreData
return/print function_three_output
def Main():
firstData = function_one(infile)
secondData = function_two(firstData)
function_three(secondData)
This is assuming your function_three would write to a file or doesn't need to return anything. Another method, if these three functions will always run together, is to call them inside function_three. For example...
def function_three(file):
firstStep = function_one(file)
secondStep = function_two(firstStep)
doThings on secondStep
return/print to file
Then all you have to do is call function_three in your main and pass it the file.
For safety, readability and debugging ease, I would temporarily store the results of each function.
def function_one():
do things
return function_one_output
def function_two(function_one_output):
take function_one_output and do more things
return function_two_output
def function_three(function_two_output):
take function_two_output and do more things
return/print function_three_output
result_one = function_one()
result_two = function_two(result_one)
result_three = function_three(result_two)
The added benefit here is that you can then check that each function is correct. If the end result isn't what you expected, just print the results you're getting or perform some other check to verify them. (also if you're running on the interpreter they will stay in namespace after the script ends for you to interactively test them)
result_one = function_one()
print result_one
result_two = function_two(result_one)
print result_two
result_three = function_three(result_two)
print result_three
Note: I used multiple result variables, but as PM 2Ring notes in a comment you could just reuse the name result over and over. That'd be particularly helpful if the results would be large variables.
It's always better (for readability, testability and maintainability) to keep your function as decoupled as possible, and to write them so the output only depends on the input whenever possible.
So in your case, the best way is to write each function independently, ie:
def function_one(arg):
do_something()
return function_one_result
def function_two(arg):
do_something_else()
return function_two_result
def function_three(arg):
do_yet_something_else()
return function_three_result
Once you're there, you can of course directly chain the calls:
result = function_three(function_two(function_one(arg)))
but you can also use intermediate variables and try/except blocks if needed for logging / debugging / error handling etc:
r1 = function_one(arg)
logger.debug("function_one returned %s", r1)
try:
r2 = function_two(r1)
except SomePossibleExceptio as e:
logger.exception("function_two raised %s for %s", e, r1)
# either return, re-reraise, ask the user what to do etc
return 42 # when in doubt, always return 42 !
else:
r3 = function_three(r2)
print "Yay ! result is %s" % r3
As an extra bonus, you can now reuse these three functions anywhere, each on it's own and in any order.
NB : of course there ARE cases where it just makes sense to call a function from another function... Like, if you end up writing:
result = function_three(function_two(function_one(arg)))
everywhere in your code AND it's not an accidental repetition, it might be time to wrap the whole in a single function:
def call_them_all(arg):
return function_three(function_two(function_one(arg)))
Note that in this case it might be better to decompose the calls, as you'll find out when you'll have to debug it...
I'd do it this way:
def function_one(x):
# do things
output = x ** 1
return output
def function_two(x):
output = x ** 2
return output
def function_three(x):
output = x ** 3
return output
Note that I have modified the functions to accept a single argument, x, and added a basic operation to each.
This has the advantage that each function is independent of the others (loosely coupled) which allows them to be reused in other ways. In the example above, function_two() returns the square of its argument, and function_three() the cube of its argument. Each can be called independently from elsewhere in your code, without being entangled in some hardcoded call chain such as you would have if called one function from another.
You can still call them like this:
>>> x = function_one(3)
>>> x
3
>>> x = function_two(x)
>>> x
9
>>> x = function_three(x)
>>> x
729
which lends itself to error checking, as others have pointed out.
Or like this:
>>> function_three(function_two(function_one(2)))
64
if you are sure that it's safe to do so.
And if you ever wanted to calculate the square or cube of a number, you can call function_two() or function_three() directly (but, of course, you would name the functions appropriately).
With d6tflow you can easily chain together complex data flows and execute them. You can quickly load input and output data for each task. It makes your workflow very clear and intuitive.
import d6tlflow
class Function_one(d6tflow.tasks.TaskCache):
function_one_output = do_things()
self.save(function_one_output) # instead of return
#d6tflow.requires(Function_one)
def Function_two(d6tflow.tasks.TaskCache):
output_from_function_one = self.inputLoad() # load function input
function_two_output = do_more_things()
self.save(function_two_output)
#d6tflow.requires(Function_two)
def Function_three():
output_from_function_two = self.inputLoad()
function_three_output = do_more_things()
self.save(function_three_output)
d6tflow.run(Function_three()) # executes all functions
function_one_output = Function_one().outputLoad() # get function output
function_three_output = Function_three().outputLoad()
It has many more useful features like parameter management, persistence, intelligent workflow management. See https://d6tflow.readthedocs.io/en/latest/
This way function_three(function_two(function_one(infile))) would be the best, you do not need global variables and each function is completely independent of the other.
Edited to add:
I would also say that function3 should not print anything, if you want to print the results returned use:
print function_three(function_two(function_one(infile)))
or something like:
output = function_three(function_two(function_one(infile)))
print output
Use parameters to pass the values:
def function1():
foo = do_stuff()
return function2(foo)
def function2(foo):
bar = do_more_stuff(foo)
return function3(bar)
def function3(bar):
baz = do_even_more_stuff(bar)
return baz
def main():
thing = function1()
print thing
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.