There are some cases where a certain piece of code needs to perform an action several times. But writing the code at all times where the action is necessary increased the code complexity. So we need an alternative to these problems. Python function provide good solutions to this. So let first have a look over
What is a python function?
The function is a block of code which provides the re-usability. These functions allow the proper modularity for the application in a single action. Python offers built-in functions like Print(). Besides, it allows the users to create the function of our own. These functions are knows as the User-defined functions.
So my readers till now we have what is a function in learn to code python, So now let us have a look over how to define a function.https://www.youtube.com/watch?v=zEPqqczgCEY&t=755s
Rules for defining a function:
- The function name should start with a def keyword followed by a function name and parenthesis.
- All the arguments and input parameters should be placed within the parenthesis
- The functional code within the function should start with the colon :
- To exit the function, we use the return (this is also used to send object return to the caller)
Syntax :def func_name():statements()retrunEx:I would like to explain this with an addition exampledef sum(x,y):z=x+yreturn zSum (20, 30) Output : 50
So in learn python for beginners, we will discuss how to call (or) how to invoke a function.
Function calling (or) function invoking :
The definition of the function would offer the name and specify the values/ parameter that should be included in a function. Once the function has given the basic structures, it can be executed by calling from the other functions. Besides this can also be called from the python prompt.As discussed above in Function calling, we can pass value by reference (or) pass by value.
Syn :Def function_name():Print()Function_name()Example:Def first():Print(‘this is the first function’)First()
These are the values passed in a function. The arguments are of 5 types.
These arguments provide a default value if nothing is provided in the function call. These have to be defined in the function definition.
Keyword arguments :
These arguments are related to the calls. With the help of parameter name caller identify the arguments
This allows skipping arguments.
Required arguments :
These are those arguments that are passed to the function in the correct order according to their positions.
Variable- length arguments :
In some cases, we need to write functions, that accept more parameter than they defined. These arguments are otherwise called as These arguments as a variable – length arguments.
also check How can you check the quality of the python code
scope of the variable :
The variables declare this have different scopes. let us discuss the usage in detailed.
Local variable :
The variables that can be accessed in a function, where it is declared. It cannot be accessed outside the body. Let us discuss the code with an example.
Ex:def first():a = 'im the lcoal variable'print(a)first()Output :Im the local variableEX :2:def first():a = 'im the lcoal variable’print(a)first()print (a)Output :im the local variablename ‘a’ is not defined
Since variable ‘a’ is defined in a function ,it cannot accessed outside the function.So we have experienced an error.
So to overcome this feature, we use Global variables
Global Variable :
This is unlike the local variable. This can be accessed globally. The variables that are declared ones can be accessed many functions.
Ex:def f():s= 'im the local function. I overrided the global function'print (s)a= 'im the local function, i cannot access the outside the function f'print (a)# Global scopeb= "Since, I am the global function, print S is called before the function, and first exected"print(s)f()a= 'i love python'print (a)
Since, I am the global function, print S is called before the function,and first exected
im the local function. I overrided the global function
im the local function, I cannot access the outside the function f
i love python
def f():s= 'im the local function. I overrided the global function'print (s)# Global scopeb = "Since, I am the global function, print S is called before the function,and first exected"print(s)f()print (b)
Since, am the global function, print S is called before the function,and first executed
im the local function. I overrided the global function
am the global function, print S is called before the function,and first executed
If you have observed the code, when the control comes outside the function, the value of the global variable will be stored.
Q: How do we access the local variable value outside the function?
So far, we have discussed the local variables as well as the global variables. But as shown above, if the control is a function outside, the memory/cache stores only the global variableSo to store the local variable value outside the memory we need to make use of Global function. let us consider the working of the global function with an example.
def f():global bs= 'im the local function. I overrided the global function'print (b)# Global scopeb = "Since, I am the global function, print S is called before the function, and first exected"print(s)f()print (b)
Iam the global function, since print S is called before the function, I was exected
im the local function. I override the global function
im the local function. I overrided the global function
So now let's move to the next topic recursion.
So till now, we have seen how to call the function and also how to pass the variables to it. But we cannot say exactly the function may call the other functions. In some cases, function calls the same functions too. This phenomenon is nothing but recursion.
In simple words factorial is a good example of recursion.
def calc_factorial(x):"""This is a recursive functionto find the factorial of an integer"""if x == 1:return 1else:return (x * calc_factorial(x-1))num = 10print("The factorial of", num, "is", calc_factorial(num))
So far, we have discussed what is a function, how to define the function and the types of functions? Now its time to discuss some functions in python.
_Init_:After the class creation __init__ called . It also known as constructor
Self represents the instance of the class. In python, using the self keyword, we can access the python class attributes and methods.
In the best way to learn to learn python, these keywords play a prominent role. So now let us have a look over the syntax and example
class SomeClass:variable_1 = “ This is a class variable”variable_2 = 50 #this is some other variabledef __init__(self, param1, param2):self.instance_var1 = param1#instance_var1 is a instance variableself.instance_var2 = param2#instance_var2 is a instance variable
class Rectangle:def __init__(self, length, breadth, unit_cost=0):self.length = lengthself.breadth = breadthself.unit_cost = unit_costdef get_perimeter(self):return 2 * (self.length + self.breadth)def get_area(self):return self.length * self.breadthdef calculate_cost(self):area = self.get_area()return area * self.unit_cost# breadth = 50 cm, length = 70 cm, 1 cm^2 = Rs 1500r = Rectangle(50, 70, 1500)print("Area of Rectangle: %s cm^2" % (r.get_area()))print("Cost of rectangular field: Rs. %s " % (r.calculate_cost()))
Here in the above example, all the values that were the length, breadth, and unit_cost were assigned to self.length, self.breadth, and self.unit_cost respectively. And all the operations were done using the self.variable_name (variable _name may be length,breadth and unit_cost).
Hope you got a better idea regarding _init_ and self.
Doc strings :
It provides a convenient way of associating documentation, with python modules, classes, functions, and methods. doc_ strings can be accessed by __doc__ attribute.
How to define a doc string?
Usually, the doc string line should start with a capital letter.
The first line should be a short description
And we should not write the object name.
def my_function():"""Demonstrate docstrings and does nothing really."""return Noneprint ("Using __doc__:")print (my_function.__doc__)
Out Put :
Demonstrate docstrings and does nothing really.
I Suggest you to practice the one line Doc string, multi-line doc strings and Doc string in classes. If you fin difficulty clarify your doubts at best online python course.
Date and Time :
The other function that we need to discuss is Date and time. Let us discuss briefly it.
A date in python is a data type of its own. But we can import a module, named date time to work with dates as well as date objects.
import datetimex = datetime.datetime.now()print(x)
It means it displays the result in a year, month, day, hour, minute, second and microsecond.
How to get the calendar?
Python allows you to print the calendar of the month. The following code allows you to print the calendar of the month.
from datetime import datetimeimport calendarcal = calendar.month(2019, 2)print ('Here is the calendar:')print (cal)
How to display the year and weekday of the week
import datetimex = datetime.datetime.now()print(x.year)print(x.strftime("%A"))
How to display the name of the month?
import datetimex = datetime.datetime(2018, 6, 1)print(x.strftime("%B"))
Now let us have a look over some Date and time legal formats.
|%a||Weekday, short version||Wed|
|%A||Weekday, full version||Wednesday|
|%w||Weekday as a number(0-6). Weekday starts from Sunday||3|
|%d||Day of the month (1-31)||13|
|%b||Month name(short version)||Feb|
|%B||Month name(full version)||February|
|%m||Month as a number(1-12)||2|
|%y||Year, short version||19|
|%Y||Year, Full version||2019|
|%j||Day number of the year||44|
|%U||Week number of the year. Sunday as the first day of the week||22|
|%W||Week number of the year. Monday as the first day of the year||52|
|%c||The local version of date and time||Wed Feb 13 15:10:54 2019|
|%x||The local version of date||02/03/2019|
|%X||The Local version of time||15:14:17|
In the previous topics, we have discussed the python list, python tuples, and python dictionaries. And these perform the Slicing operation. Basically, these tuples/dictionaries contain a group of elements. But in all the cases, we do not require to display the complete list of elements. (It is enough to display only some elements). In those cases, we use a concept of slicing.
A slice object specifies how to slice the sequence. Here, you can specify where to start and where to end the sequence. The slice function returns a slice object.
Slice (start , end ,step)
|start||An integer specifying the position to start slicing. Its default value is zero. It is optional|
|End||An integer specifying the end of the slicing|
|Step||An integer specifying the step of slicing. Its default value is one|
temp= ("Online", "IT", "Guru", "Training", "Education", "and", "placement", "centre")x = slice(3, 5)print(temp[x])
Out put :