Reputation:
Hello I have one question.I am reading book and the chapter is about function calling another function.there is given this code:
def now_say_it(content):
print(content)
def say_something():
what_to_say = "Hi"
now_say_it(what_to_say)
say_something()
and there is said that "Note: The function that is called must be earlier in your code than the function that calls it." So it means that in def say_something() we are calling for now_say_it function right? as I understand in his note he says that this now_say_it function(def now_say_it) must be before(above) function say_something(def say_something).Am I right?
But when I write like this :
def say_something():
what_to_say = "Hi"
now_say_it(what_to_say)
def now_say_it(content):
print(content)
say_something()
it still works.But why the author wrote that note? or I assembled code incorrectly? The book I am reading is "A smarter way to learn python" by Mark Myers(chapter 50: Functions within functions)
P.s.Please advise me some good books to learn Python
Upvotes: 0
Views: 94
Reputation: 1957
Python is interpreted. Which means it reads the code line by line. The only statement of yours that is executable is this
say_something()
The other statements are only function definitions.
By the time the code comes to this point, the the two functions are already interpreted and exist. Hence it works.
You should try playing around this in a python shell. That will give you a better idea.
Upvotes: 0
Reputation: 1413
What the author means is that you need to declare the function before calling it in chronological order. That is, this will work:
def say_something():
what_to_say = "Hi"
now_say_it(what_to_say)
def now_say_it(content):
print(content)
say_something()
or, this as well, will work:
def now_say_it(content):
print(content)
def say_something():
what_to_say = "Hi"
now_say_it(what_to_say)
say_something()
but this wont work:
def say_something():
what_to_say = "Hi"
now_say_it(what_to_say)
say_something()
def now_say_it(content):
print(content)
Upvotes: 1