Functions, Parameters, Keyword Arguments, Return Statements in Python
Day 9 in #100DaysOfCode
Functions
As our programs grow, we need to break up our code into smaller, more manageable, and more maintainable chunks we call functions. They can perform specific tasks. We use the "def" keyword which is in short for define when creating a function. When the Python interpreter sees this, it knows we are defining a function. Important note: Whenever we define a function, we have to add two empty lines after it. Example: Let's define a function that greets users.
def greet():
print("Welcome!")
print("How are you?")
print('Start')
greet()
print('Finish')
The result will look like this:
Start
Welcome!
How are you?
Finish
Parameters
It is for passing information to your users. Inside the parenthesis, we can add parameters that are placeholders for receiving information. For example, we can add a name parameter, and pass the name of the user when calling the specific function.
Example: We can add multiple inputs with parameters.
def greet(name):
print(f'Hi {name}!')
print("How are you?")
greet("İlke")
greet("Jack")
Result:
Hi İlke!
How are you?
Hi Jack!
How are you?
PS: Arguments, are the actual pieces of information that we supply to these functions.
Keyword Arguments
In these arguments, positions don't matter while in positional arguments it does. Keyword arguments are helping us to improve the readability of our code.
def team(name, project):
print(name, "is working on a", project)
team(project="code", name='İlke')
Result:
İlke is working on a code
->If you are dealing with functions that take numerical values, see if you can improve the readability of your code using keyword arguments. ->If you are using both positional and keyword arguments, keyword arguments should always come after positional arguments. Example:
greet( "İlke", last_name="Bengi")
Return Statements
We are going to create functions that return values. This is extremely beneficial if you are doing a calculation in your function and you want to return to result to whoever using your function. Example:
def square(number):
print(number*number)
print(square(5))
Result:
25
None