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
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.
Syntax : def func_name(): statements() retrun Ex: I would like to explain this with an addition example def sum(x,y): z=x+y return z Sum (20, 30) Output : 50
So in learn python for beginners, we will discuss how to call (or) how to invoke a function.
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.
These arguments are related to the calls. With the help of parameter name caller identify the arguments
This allows skipping arguments.
These are those arguments that are passed to the function in the correct order according to their positions.
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
The variables declare this have different scopes. let us discuss the usage in detailed.
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 variable EX :2: def first(): a = 'im the lcoal variable’ print(a) first() print (a) Output : im the local variable name ‘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
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 scope b= "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 scope b = "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 variable
So 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 b s= 'im the local function. I overrided the global function' print (b) # Global scope b = "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 function to find the factorial of an integer""" if x == 1: return 1 else: return (x * calc_factorial(x-1)) num = 10 print("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.
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 variable def __init__(self, param1, param2): self.instance_var1 = param1 #instance_var1 is a instance variable self.instance_var2 = param2 #instance_var2 is a instance variable
class Rectangle: def __init__(self, length, breadth, unit_cost=0): self.length = length self.breadth = breadth self.unit_cost = unit_cost def get_perimeter(self): return 2 * (self.length + self.breadth) def get_area(self): return self.length * self.breadth def calculate_cost(self): area = self.get_area() return area * self.unit_cost # breadth = 50 cm, length = 70 cm, 1 cm^2 = Rs 1500 r = 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.
It provides a convenient way of associating documentation, with python modules, classes, functions, and methods. doc_ strings can be accessed by __doc__ attribute.
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 None print ("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.
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 datetime x = datetime.datetime.now() print(x)
It means it displays the result in a year, month, day, hour, minute, second and microsecond.
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 datetime import calendar cal = calendar.month(2019, 2) print ('Here is the calendar:') print (cal)
import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A"))
import datetime x = 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 :
to our newsletter
Azure is a great Microsoft Cloud Computing platform in providing various cloud services through online. ITGuru Certified Azure Architect certification course gives you the practical knowledge on Azure Cloud platform through real-world use cases from live experts
Getting knowledge of cloud platforms like ServiceNow is essential in today’s world for the smooth running of projects in cloud platform. Turn your dream to the reality of becoming the Certified ServiceNow Administrator through ServiceNow Administration online certification Course with practical examples by live industry experts through online at ITGuru with real-world use cases.
knowing the basics on any platform like Workday is not enough to sustain the IT industry. Hence it is essential to go beyond on Workday basics like Workday Financials training which lets you know the application of Financials management in real -world use cases from ITGuru Live Experts in a practical way.
An organization is considered as the best one when it offers the best benefits to the employee. Moreover, the greater the employee benefits, the greater the contribution to the organization. ITGuru let you know the practical workday Human Resource Management(HRM) features with live examples by experts
Turn your dream into reality by ITGuru live experts with real-world use cases through practical knowledge on python online course and become the certified associate in python programming and become a master in python programming
Python is the trending programming language in the IT industry. Mastering in python programming gives you more value among the people in the IT industry. Hence start today to learn python programming online by live experts with real-time uses cases at ITGuru