Edit: The suggested duplicate, does not answer my question, as I am primarily concerned with the difference in Python specifically. The suggested duplicate is far broader than this question.
I have recently started to learn Python. I'm currently reading "Learn Python the Hard Way". I have some ad-hoc programming experience, but am going back to the beginning to learn everything from the ground up this time.
In the book, one of the first lessons concerns print and the author provides various instructions of its use in Python 2.7, e.g.:
print "This is fun."
I found myself wondering what print is technically called here from the programming perspective. Some research found this, PEP-3105
In which case is made to make print a function:
The print statement has long appeared on lists of dubious language
features that are to be removed in Python 3000, such as Guido's
"Python Regrets" presentation 1 . As such, the objective of this PEP
is not new, though it might become much disputed among Python
developers.
So print is a statement in Python 2.7, and a function in Python 3.
But I have been unable to find a straight-forward definition for the difference between a statement and a function. I found this also by the person who invented Python, Guido van Rossum in which he explains why it would be good to make print a function instead of a statement.
From what I have read it appears that a function is some code that takes parameters and returns a value. But isn't print doing this in python 2.7? Isn't it taking in strings and returning a concatenated string?
What is the difference between a statement and a function in Python?
A statement is a syntax construct. A function is an object. There's statements to create functions, like def:
def Spam(): pass
So statements are one of the ways to indicate to Python that you want it to create a function. Other than that, there's really not much relation between them.
A statement in Python is any chunk of code you've written. It's more a theoretical concept than a real thing. If you use the correct syntax when writing your code, your statements will get executed ("evaluated"). If you use the incorrect syntax, your code will throw an error. Most people use "statement" and "expression" interchangeably.
Probably the easiest way to see the difference between a statement and a function is to see some example statements:
5 + 3 # This statement adds two numbers and returns the result
"hello " + "world" # This statement adds to strings and returns the result
my_var # This statement returns the value of a variable named my_var
first_name = "Kevin" # This statement assigns a value to a variable.
num_found += 1 # This statement increases the value of a variable called num_found
print("hello") # This is a statement that calls the print function
class User(BaseClass): # This statement begins a class definition
for player in players: # This statement begins a for-loop
def get_most_recent(language): # This statement begins a function definition
return total_count # This statement says that a function should return a value
import os # A statement that tells Python to look for and load a module named 'os'
# This statement calls a function but all arguments must also be valid expressions.
# In this case, one argument is a function that gets evaluated
mix_two_colors(get_my_favorite_color(), '#000000')
# The following statement spans multiple lines and creates a dictionary
my_profile = {
'username': 'coolguy123'
}
Here is an example of a statement that is invalid:
first+last = 'Billy Billson'
# Throws a Syntax error. Because the plus sign is not allowed to be part of a variable name.
In Python, you tend to put each statement on their own line, except in the case of nested statements. But in other programming languages like C and Java, you could put as many statements on a single line as you wanted as long as they are separated by a colon (;).
In both Python2 and Python3, you can call
print("this is a message")
and it will print the string to standard out. This is because they both have a function defined called print that takes in a string argument and prints it.
Python2 also allowed you to make a statement to print to standard out without calling a function. The syntax of this statement was that it started with the word print and whatever came after was what got printed. In Python3 this is no longer a valid statement.
print "this is a message"
Both function and statement are words that Python understands.
Function needs parenthesis to act on anything (including nothing).
Statement does not.
Hence in Python 3 print is function not statement.
Let us take a funny case. not True and not(True) both work. But type(not) is not function hence not is statement. not(True) works only because Python takes parenthesis also for grouping. Bad design, indeed.
Another difference: (not) fails, (print) does not fail, because a statement has no value while a function has one (for the interpreter, not in the mathematical sense of the image of some antecedent).
Related
def enumerator(fruits):
for index, fruit in enumerate(fruits):
print(f"Fruit: {fruit}, under the index: {index}.")
just_a_variable = enumerator(["apple", "banana", "lemon"]) # Im just assigning function call
# to the variable "just_a_variable"
# and boom, when I run the program the function is called. Makes no sense (it shouldn't work this way, does it?)
I assume this is happening because there is a print statement in the function but it still doesn't make sense. if I change the print statement to "return" it suddenly doesn't compile, that is what I was expecting from just using print. I'm I missing something here?
In general if you add parenthesis after a function (like one of the two examples below), it is called.
function_name(arguments)
variable = function_name(arguments)
If you just want a variable to point to a function:
variable = function
Then the following two statements will become identical:
variable(arguments)
function(arguments)
Having said so, this seems a bit useless to me. With you function defined the way it currently is, there isn't a way I know to "assign" it to a variable and pass arguments at the same time.
This does change the structure of your code, but you can perhaps use yield instead of return.
The line just_a_variable = enumerator(["apple", "banana", "lemon"]) is calling function enumerator. Technically, that is what the parenthesis after enumerator do.
Perhaps you noticed that simply running the file is running that line (and calling enumerator). As a scripting language, this is how Python works (in contrast to Java or other compiled languages).
Apparently, this:
def f():
pass
# maybe the function is over
pass # oh wait, it's not
f()
is valid syntax, whereas this is not:
def f():
pass
''' maybe the function is over '''
pass # oh wait, it's not
f()
That comes as a huge surprise to me. So my questions are:
Why? Why does Python not consider the first version to be a syntax error?
Is there anything in PEP8 recommending that this not be done?
Yes the first one is valid because it starts with # which defined in the language to be a comment line so it's ignored and its indentation won't end functions or start new ones.
The latter is different, it's a string evaluated but its value is never used, you could use that to achieve multi line comments but still the interpreter will try to evaluate that string as code, so the indentation of this string matter to the interpreter and it could end scopes.
for the second one writing something like
'''comment''''
is as much code to the interpreter as this
my_var = '''comment'''
But this
# comment
is ignored and is not code to the interpreter.
Lets say I have the function:
def function(a)
c = a+b
print(c)
Is it advisable to use the print statement in the function to display output rather than placing a return statement at the end and using the print(function(a))?
Also what implications would there be if I used both a print statement and a return statement in a function to display the same output? Lets imagine I need to show the answer for c and then use the value of c somewhere else. Does this break any coding conventions?
So the highlight of the question isn't the difference between print and return, but rather if it is considered a good style to use both in the same function and if it has a possible impact on a program. For example in:
def function(a)
c = a+b
print(c)
return c
value = function
print(value)
Would the result be two c's? Assume c = 5; therefore, would the output be(?):
5
5
print and return solve two completely different problems. They appear to do the same thing when running trivial examples interactively, but they are completely different.
If you indeed just want to print a result, use print. If you need the result for further calculation, use return. It's relatively rare to use both, except during a debugging phase where the print statements help see what's going on if you don't use a debugger.
As a rule of thumb I think it's good to avoid adding print statement in functions, unless the explicit purpose of the function is to print something out.
In all other cases, a function should return a value. The function (or person) that calls the function can then decide to print it, write it to a file, pass it to another function, etc.
So the highlight of the question isnt the difference between print and
return but rather if it is considered good style to use both in the
same function and its possible impact on a program.
It's not good style, it's not bad style. There is no significant impact on the program other than the fact you end up printing a lot of stuff that may not need to be printed.
If you need the function to both print and return a value, it's perfectly acceptable. In general, this sort of thing is rarely done in programming. It goes back to the concept of what the function is designed to do. If it's designed to print, there's usually no point in returning a value, and if it's designed to return a value, there's usually no point in printing since the caller can print it if it wants.
Well return and print are entirely two different processes.
Whereas print will display information to the user or through the console; and return is used for collecting data from a method that fulfills a certain purpose (to use later on throughout your program).
And to answer your question, I believe it would return the two values; since one prints the c variable itself, and the other returns the value c to present as well? Correct me if I'm wrong.
I new in Python. I don't know how work this.
I have this code:
def main():
a=input("Type number")
e=int(a)
function2(e);
def function2(e):
for h in range(e):
print("X")
main();
write me this error:
Traceback (most recent call last)
for h in range(e):
NameError: name 'e' is not defined
Thats because of an indentation error, and you forgot to put a : after your for loop:
def main():
a = input("Type number")
e = int(a)
function2(e)
def function2(e):
for h in range(e):
print("X")
main()
Also, no semicolons are required in python.
Your problem seems to be a series of misunderstandings in general. Your errors in your code are simple, but let's see if I can't walk you through some concepts so that when I show you the fixed code, you understand it completely. Keep in mind that I expect you already know a lot of it, but I'm writing this answer not just for you, but for any other beginners who stumble upon this page. :)
It seems we can cover the following topics (each concept is simple in itself, but you need to get them completely in order to get the next one):
Variables in programming
Variables in python
Whitespace in python
Functions: Parameters vs Arguments
Solution: fixing your code
Variables in programming
Variables, as you probably know, are simply the labels we give to data. In most languages, you have to declare the variable first so that you can have the appropriate type assigned to it (that is, so the computer knows whether it's an integer, a string, a boolean, etc). Thus, you need the following code:
int myVariable1 = 3;
string myVariable2 = "hello";
bool myVariable3 = true;
(In some languages, you need to declare variables and then assign a value to them.)
Variables in python
Python, apart from many starter languages, is dynamically typed. This means that the variables (the labels on the data) have no type, but the values do.
That means that your code can look like this
myVariable1 = 3
myVariable2 = "hello"
myVariable3 = True
And python can figure out what types to use, based on the data assigned to the variables.
(Note: in python, you don't need ; to end a line, and boolean values are capitalized (True, `False))
Whitespace in python
Python was designed to be easy to read. Computers use hints inside the language ((), [], {}, :, ;, etc) to know what's going on. In Python, whitespace ( ) is part of the hinting, or syntax. In most languages, whitespace is ignored but because Python does not ignore it, it can be used to format your languages in a visually pleasing way. In C++,
function myFunction() {string myString = "wow such learn good job, many doge wow";}
and
function myFunction() {
string myString = "wow such learn good job, many doge wow";
}
are the same. You can see how this could confuse a new programmer, as it doesn't even look the same. But in Python, the code has to look like:
def myFunction():
myString = "wow such learn good job, many doge wow"
And it is this uniformity that makes Python so much easier to work with, for a lot of people.
Functions: Parameters vs Arguments
In every decent language, the use of functions is vital, and understanding them completely is even more vital.
Functions can easily be related to basic concepts of Algebra. Functions already exist in Algebra, this being why the comparison is so easiy.
In Algebra, a function is an equation with variables in it. Inside the function, work is ready to be done with the equation that is set up, and it's just waiting for you to fill in the missing pieces. That is to say,
f(x) = 3 + 2x + x^2
is a function that is ready to go, but it needs to you put in x.
This is the same thing in programming. When I write
def myFunction(x):
3+2x+x**2
I am writing the exact same thing as f(x); A working equation that depends on the information it is given.
A note: Not all programming functions do math exactly, some operate on strings, but they all alter data and that is my point. Some functions don't even need input, because they operate on data independent of what you're doing. Here, the comparison falls apart somewhat, but I hope you're still onboard.
So, what are arguments and what are parameters?
When defining the function and then calling the function:
def myFunction(x): #defining the function f(x)
3+2x+x**2
print myFunction(3) #calling the function f(x) where x=3
The parameter is x in the first line. Parameters are the variables that you put into the definition of a function.
The argument is the 3 that you put in place of the x when you called the function. Arguments are the values you use to fill in the variables in a function.
As such, you are now giving the function the value 3 and it solves the following:
3+2*(3)+(3)^2
3+6+9
9+9
18
The resulting output will of course print:
18.
Solution: fixing your code
Now that we've gone over all of the base concepts that lead to your code getting errors. Here is your original code:
def main():
a=input("Type number")
e=int(a)
function2(e);
def function2(e):
for h in range(e):
print("X")
main();
There are a multitude of errors here:
Your def main(): is written mostly correct, but the indentation may not be sufficient. Python standard, the one that may confuse less sophisticated interpreters for it, requires about 4 spaces as its whitespace and indentation.
Your def main(): also uses a ; at the end, which, as a difference between Python and lots of other languages, is a syntax problem. Python doesn't need ;, and just removing it fixes that error.
Your def function2(e): appears to have no errors aside from the whitespace problem that we saw in def main():
Your def function2(e): makes use of print(), which, while this is no error, is a syntax difference that is significant between Python 2.7 and Python 3.3; For this reason, I'll be adding the tag Python 3.3 for future-proofing reasons.
When you call main();, the ending ; is unneccessary, and can be removed.
Here is a revised version of your code that works.
def main():
a = input("Type number")
e = int(a)
function2(e)
def function2(e):
for h in range(e):
print("X")
main()
Do you understand how it works completely now? Sorry for all the reading, hopefully you are much more comfortable now, having gone through the entire thing!
For any questions, don't hesitate to ask in a comment below.
Happy Coding!
PS - I see that you already picked the best answer. But maybe after reading this one, you'll change your mind ;)
You're missing a colon : inside of your function2, so if you change that bit to:
def function2(e):
for h in range(e):
print("X")
You should be good to go.
None Any mistake or synatx erorr in Your Code It is Working Fine .
And You can indent the code by (tab) or by one space or any thing else .as long as you are saved the Blocks
I'm up to Exercise 41 in Learn Python the Hard Way, and I'm having a really hard time wrapping my brain around the fact that the entire thing hinges on a function running just because it's been assigned as a value to a variable. I wrote up a little script to confirm that this is how it works, and it does:
def pants():
print "Put on some pants!"
def shorts():
print "And don't forget your underwear!"
zap = pants()
thing = shorts()
With the results being:
Put on some pants!
And don't forget your underwear!
So obviously this happens, but I can't understand why the language works that way -- what the logic is behind the language that makes this a valuable way of operating. I think it'd be helpful for me moving forward to understand why this is, rather than just "that's the way it works."
For clarity: I'm asking (I guess) why the function is running, when all I'm doing is assigning it as a value for something. The print statements are just there so I can see that the function is indeed running.
It's the fact that I'm not ever actually running
pants()
shorts()
that is confusing me.
To create a tortured analogy, if me-baking-cookies-at-home were "cookies()", and I were to make cookies on Saturdays, I might eventually believe that
Saturday = cookies()
but just thinking "hey, Saturday is cookie day" is not the same as actually baking cookies... so why does just saying
Saturday = cookies()
actually bake the cookies, rather than just setting up Saturday with the variable "cookies()" for some later use?
When you use the parentheses () the function gets called. If you want to assign the function to the variable to reuse it you should remove there parentheses.
Example:
def pants():
print "Put on some pants!"
def shorts():
print "And don't forget your underwear!"
zap = pants
thing = shorts
And then when you want to call those functions:
zap()
thing()
So obviously this happens, but I can't understand why the language works that way -- what the logic is behind the language that makes this a valuable way of operating. I think it'd be helpful for me moving forward to understand why this is, rather than just "that's the way it works."
The language needs some way to distinguish between the function and the act of calling the function. That is what the parentheses provide.
f = foo
Now f is bound to the function itself. The function foo could be executed by f().
f = foo()
This calls the function foo and binds the return value to f.
Note that whether or not you bind the return value to a name is irrelevant. Simply writing
foo()
will also execute the function but the return value will simply be ignored.
Although it may seem like your functions don't return anything, they do in fact. Quoting the Python.org documentation:
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.
So your functions really look like this:
def pants():
print "Put on some pants!"
return None
def shorts():
print "And don't forget your underwear!"
return None
Your assignments assign to zap whatever pants returns (i.e. the value of pants()), and to thing whatever shorts returns. In your case, both are None, but of course the functions must be run in order to figure this out(*). Afterall, it could be that pants returns 42 during leap years, and that shorts returns 'Foobar' whenever some random number generator "rolls" a 6.
(*) Digression: That the functions "must be run" should not be considered universally true. In a pure setting, and leaving aside the specifics of Python (of which I know very little), a compiler might realize that both functions are identically None, and cause no calls to be made when the program is run. But a function that prints something (or inspects whether the current year is a leap year, or rolls a die) won't be pure.
zap = pants() will bind the return value of the function to the variable, so of course the function is run if you bind it to a variable.
def foo():
return 1
var = foo()
print var
will print 1.
I hope this helps.
Edit: If you expect the value of the variable to be "put on some pants", you are indeed confusing print and return, as people pointed out in the comments.
When the interpreter sees a function name followed by () it knows that it's supposed to execute that function.
What you're doing there is saying "assign the result of these functions to these variables".
But since you are not returning any values from those functions, you're not seeing anything in the variables.
However because you have a print statement in there, you are seeing the interpreter execute those functions as it attempts to assign the variable to results of that function.
Your functions are called because of the parenthesis after the name:
zap = pants()
This calls the function pants and puts the result in zap. If you had done this instead:
zap = pants
then zap would now refer to the pants function itself.
And if you just wrote
pants()
then the pants function would also get called, but the result (which is None) would never have been put in a variable.
From your question what I think you want zap will have the value "Put on some pants!" and thing will have the value "And don't forget your underwear!". If that is your problem let's discuss it. Otherwise you do not need to read further as I just discussed about all that.
Let's make it some fun. When you define a function, you are like creating a machine that does what you want it to do. Now let's think of a machine that when you give some food in it, it chops them and ... does nothing! I mean I made that machine to chop foods and nothing else! You won't get your chopped food back, but indeed it chopped your food as you made it for.
Now, as you want your chopped food back, you create another machine that takes your food, chops them and return them to you. Fruitful machine, isn't it? ;-)
They are all true for functions in programming or math (though I don't know any void function in math! :P). When you are creating the function, you have to tell it whether it just does some work or it does some work and return the result. The way to tell a function is the return statement. In your functions, you have just told to do something. And that is print "......" so does the functions. You call the with () at end and the does their work, they prints it. But as I said if you don't tell it to return a result, it won't. And because it is not returning any result, nothing will be assigned with the variable (don't confuse him with None). When you wrote those lines (if in interpreter) or run the script, you will see those lines printed but your zap and thing has no values.
So how to fix it? Tell them to return the lines to the variables. To tell the functions do that, replace the print statements with return statements. And never mind to experiment what you know, to know about what you know about your knowledge is true :-)
Hope it helps :-)