I purchased a course on udemy during one of their 75% off sales not that long ago. The course is called “Learn Python, it's CAKE (Beginners).” It’s taught by Jason Elbourne.
Jason begins his chapter on functions by assembling the following code sample:
Code:
1 def print_name(name='Jason'):
2 print name
3 print_name('Josh')
I had difficulty learning from that code. So I turned to Google and came across, “Think Python: How to Think Like a Computer Scientist.” According to this guide:
Quote:
Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next follows the block of statements that are part of this function.
|
This quote is from Marios Zindilis's
section on functions in A Byte of Python 2.
I came across another book called, Python for Software Design: How to Think Like a Computer Scientist authored by Allen B. Downey. Downey's
chapter on functions has helped me.
The only issue I have with Downey's guide is that its all done in the CLI Python interpreter. I prefer to use a text editor. Here is the example in Think Python which I adapted to be executed from file:
Code:
1 def print_twice(bruce):
2 print bruce
3 print bruce
4
5 michael = 'Eric, the half a bee.'
6 print_twice(michael)
This is easier for me to understand I think. I have written an analogy in my effort to help determine how well I understand how this function in particular works.
Functions work like a telephone. The name of the function - - defined at line 1 - - “print_twice” - - is like a phone number which must be unique. You can’t use one phone number to reach two people. In line 1, “(bruce)” is a placeholder for an argument to be specified by the user each time the unique name is called in the future. “print bruce” at lines 2 and 3 are the operations performed, kinda like a voicemail message. Dialing (or calling) one unique number (a function) will connect you one person's voicemail answering machine, while dialing another unique number (a different function) will connect you to a different person. At line 4, “michael” is a variable with a string attributed to it. At line 6, the user passes the newly defined variable as the argument as it calls the function defined in lines 1 through 3.
Getting back to the phone analogy, some phone messages are longer and more complicated than others. In this case, the message is a useless simple print statement. There are other functions, like for Physicists and Engineers, which are used to perform complicated algorithms. I can see how useful functions could be for these scientists. I suppose I am working with print statements because I am a beginner who majored in Philosophy?
Have I demonstrated an accurate basic understanding of how to use functions in Python? If not, then could someone please add something or correct me? Am I way off? Or am I on the right track?