In this Python Beginner Tutorial, we will begin learning how to write functions. Functions are one of the most important things to learn in Python Programming and will take us to the next level. We will learn how to create/define functions, how to pass in arguments, and also how to return values. Let's get started.The code from this video can be found at:Watch the full Python Beginner Series here:Scope Video:✅ Support My Channel Through Patreon:✅ Become a Channel Member:✅ One-Time Contribution Through PayPal:✅ Cryptocurrency Donations:Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3Ethereum Wallet - 0x16068fB817101d3bCD33Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot✅ Corey's Public Amazon Wishlist✅ Equipment I Use and Books I Recommend:▶️ You Can Find Me On:My Website -My Second Channel -Facebook -Twitter -Instagram.
What is a function in Python?In Python, function is a group of related statements that perform a specific task.Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.Furthermore, it avoids repetition and makes code reusable. Syntax of Functiondef functionname(parameters):'docstring'statement(s)Above shown is a function definition which consists of following components. Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same. Parameters (arguments) through which we pass values to a function. They are optional. A colon (:) to mark the end of function header.
![Python Python](/uploads/1/2/5/6/125629640/381109129.png)
A function in Python is defined by a def statement. The general syntax looks like this: def function-name(Parameter list): statements, i.e. The function body The parameter list consists of none or more parameters. Parameters are called arguments, if the function is called. The function body consists of indented statements. Python programmers, trainers, students and book writers should feel free to bypass these functions without concerns about missing something important. Apply ( function, args , keywords ) ¶ The function argument must be a callable object (a user-defined or built-in function or method, or a class object) and the args argument must be a sequence.
Optional documentation string (docstring) to describe what the function does. One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces). An optional return statement to return a value from the function.Example of a function. Note: Try running the above code into the Python shell to see the output.DocstringThe first string after the function header is called the docstring and is short for documentation string.
![Python Python](/uploads/1/2/5/6/125629640/685803955.png)
It is used to explain in brief, what a function does.Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines.
This string is available to us as doc attribute of the function.For example:Try running the following into the Python shell to see the output. print(greet.doc)This function greets tothe person passed into thename parameterThe return statementThe return statement is used to exit a function and go back to the place from where it was called. Syntax of returnreturn expressionlistThis statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.For example: print(greet('May'))Hello, May. Good morning!NoneHere, None is the returned value. Example of return. Def absolutevalue(num):'This function returns the absolutevalue of the entered number'if num = 0:return numelse:return -num# Output: 2print(absolutevalue(2))# Output: 4print(absolutevalue(-4))How Function works in Python?Scope and Lifetime of variablesScope of a variable is the portion of a program where the variable is recognized.
Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope.Lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes.They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.Here is an example to illustrate the scope of a variable inside a function. Def myfunc:x = 10print('Value inside function:',x)x = 20myfuncprint('Value outside function:',x)Output Value inside function: 10Value outside function: 20Here, we can see that the value of x is 20 initially. Even though the function myfunc changed the value of x to 10, it did not effect the value outside the function.This is because the variable x inside the function is different (local to the function) from the one outside.
Although they have same names, they are two different variables with different scope.On the other hand, variables outside of the function are visible from inside. They have a global scope.We can read these values from inside the function but cannot change (write) them.
In order to modify the value of variables outside the function, they must be declared as global variables using the keyword global.Types of FunctionsBasically, we can divide functions into the following two types:. Functions that are built into Python. Functions defined by the users themselves.