“Functions in Python can be defined as lines of codes that are built to create a specific task and can be used again and again in a program, when called.”
There are two types of functions in Python language:
We have used a lot of built-in functions in our code till now, these functions include print(), or sum(), etc. So, we have a good idea about how to call a function. Built-in functions are already present in our python program, and we just have to call them whenever we need them to execute. Being familiar with built-in functions we will now look into User-defined function mostly in this tutorial.
We must know how to define a function in Python in order to create one ourselves. We have to use the def keyword in order to define a function accompanied by the functions name with a pair of parentheses. The function of parenthesis is to send arguments or parameters to a function. In simple words parameters can be defined as values that are sent in the parenthesis. For example, if a function is used to add two numbers then both the numbers will be passed as parameters in the parenthesis. After parenthesis, a colon is used to get in the body of the function. Some functions may return a value to the caller, so in order to get the value, a return statement is put at the end of the body of function that gives the value that has been calculated by the function.
Calling a function is very simple, we just have to write the name of the function along with closed parenthesis. If the function requires some arguments then we write those in the parenthesis, but if it does not return anything, then we leave them empty.
We have discussed a lot about what functions are and how to use them, now let us move to the advantages of using a function:
Doc string is a short form of documentation string. Its purpose is to give the programmer a brief knowledge about the functionality of the function. It must be the first string in a function, and it is also an optional string but always good to have it while working on programs having multiple functions. The syntax for writing a docstring is very simple as it is just a string written in between three doble quotes placed three times (“””) on either side of the string. But it has to be the first line of code in the function’s body. To call a docstring we write the name of the function followed by ._doc_ .
# list1 = [ ["Harry", 1], ["Larry", 2], # ["Carry", 6], ["Marie", 250]] # dict1 = dict(list1) # # for item in dict1: # print(item) # for item, lollypop in dict1.items(): # print(item, "and lolly is ", lollypop) items = [int, float, "HaERRY", 5,3, 3, 22, 21, 64, 23, 233, 23, 6] for item in items: if str(item).isnumeric() and item>=6: print(item)
No downloadable resources for this video. If you think you need anything, please post it in the QnA!
Any Course related announcements will be posted here