In this chapter, let us create Python functions and used them in various areas! When you need to put a block of codes and only called them when you need them then you will put them under the python function. Python function accepts parameters that you can pass through the function called. A python function can return nothing but it can also return a value.
The def keyword is used to define a python function. Let us look at a few examples on how to create a python functions and then use them later!
Create a Python’s function to print a range of numbers:-
def print_hi(): for number in range(3,13): # indent the code as per suggested in the previous article. print(number) print_hi() # This is how you called the above function
Create a function to print word:-
def print_hi(parameter): print(parameter) # This function will use the parameter which has been passed to it print_hi("Hello")
Create a function to print more than one parameter:-
def print_hi(parameter1, parameter2): print(parameter1 + parameter2) print_hi("Hello", " World") # Hello World
Create a function that will print out all the arguments that have been passed into that function:-
def print_hi(*args): print(args + args) print_hi("Hello", " World") # same as the previous function except for this time you are using the *args parameter
Create the function which will print out the arguments of the entry:-
def print_hi(**kwargs): print(kwargs["hello"] + kwargs["world"]) print_hi(hello = "Hello", world = " World") # same as the previous function except for this time you will need to specify the name of the parameters within the function call.
Besides that, here is another method to achieve exactly the same result without using the *kwargs parameter.
def print_hi(hello, world): print(hello+world) print_hi(hello = "Hello", world = " World")
Create a default parameter of a function:-
def print_hi(hello, world=" world"): print(hello+world) print_hi("Hello") # if you do not enter the second parameter that function will use the default one instead.
But this will generate an error…
def print_hi(hello="Hello", world): # SyntaxError: non-default argument follows default argument print(hello+world) print_hi(" World")
Create a function that will return a value:-
def print_hi(a,b): return a+b print(print_hi(10,6))
Sometimes you would like to create an empty function first inside your code and fill in the details later, then you will use the pass keyword within that function to avoid an error getting generated!
def print_hi(): pass
Create a python function that prints 10 stars on the screen:-
def print_hi(): str = '' star = "*" for a in range(10): str += star print(str) # **********
Python function is the core of Python programming language thus understanding it is a must if you want to master the Python programming language courses.