It must be followed by the function name and the parenthesized list of formal parameters. The keyword def introduces a function definition. ![]() Otherwise, the function acts just as any another Python object: > hello_world > type ( hello_world ) function Syntax components of a basic Python function Note that the parentheses have to be included to indicate that we want to execute the function. The function's code only executes when we call the function by name: > hello_world () Hello world ! Nothing should happen because nothing is being executed when we're simply defining Jump into the interactive Python shell and type out the code above. Here's a very basic function: def hello_world (): print ( "Hello world!" ) Check out Al Sweigart's Chapter 3: Functions, via Automate the Boring Stuff for a good walkthrough that covers functions and some of their related topics. ![]() The rest of this guide focuses on the bare syntax for defining functions. Defining our own functions let's us, at a bare minimum, clean up our scripts and make things much more readable.ĭefining a Python function is almost as easy as using them, but more complicated than assigning a variable.īasically, we use the def keyword, then pick a name, and then write the code we want to save for later execution as an indented block. Why do we want to define our own functions? Because we're lazy, and we're tired of having to copy and paste the same code, over and over, when we need to do something repeatedly. print) and call it with the appropriate arguments: print ( "hello world", "it's", "me" ) Defining our own Python functions By having all the Python instructions needed to print to screen wrapped up in the label, print, we just have to remember that label (i.e. Imagine typing all of those instructions just to print something to screen. The actual code that does that work is much more complex than you probably thought: ![]() It's a name assigned to a block of code that handles the work of taking an argument – "hello world" – and printing it to screen. The token print is not a special Python keyword. We've been using functions from the very start: print ( "hello world" )
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |