Learning Python - 5th Day (Part 1)
Watched this tutorial: Click here
I learned about functions() in python.
Just like java and c++ Python also has functions.
Let me demonstrate what a function is,
Imagine you have 5 books. You want to know the name of all books with just one line of code.
So you might write the code like:
if I give a command:
Tell me the name of first book
Tell me the name of second book
Tell me the name of third book
Tell me the name of forth book
Tell me the name of fifth book
This will work, but you can see the code looks larger. It would be really helpful if I just write (tell_all_book_names) and all books name were given. Well python does not have that function built in for you. But you can make your own function.
Example:
tell_all_book_names:
Tell me the name of first book
Tell me the name of second book
Tell me the name of third book
Tell me the name of forth book
Tell me the name of fifth book
if I give a command:
tell_all_book_names
Does this look simplified? Even if I want I can use the function tell all book names as many times as I need to.
In Python in order to define a function you need to write def before writing the name of the function and a double first bracket () after the name of the function.
Example:
def printNum():
print(1234)
print(' Shad')
printNum()
Output:
1234 Shad
This is how function works.
Wait we learned function right?
But see if I run the function printNum() it only prints a default value which is 1234 Shad. But what if I want to print any specific text and number.
Like I don't want to print 1234 Shad , I want to print 420 Rohan
To do this we need to pass arguments in the function. The function should ask for the value and text to print.
Example:
def printNum(val,txt):
print(val)
print(txt)
printNum(420,'Rohan')
This is how functions ask for values. In a sentence function is like a processor. You give an Input, it gives an output.
Okay we have printed the val and txt from inside the function. What if we want to know the string to print from inside the code. The function should tell this to us right?
Here the return statement comes in action.
Example:
def calculator(val):
return val + 10
print(calculator(50))
Output:
60
This is how you process any kind of arguments as many times as you want with a simple function.
More about functions:
4.7. Defining Functions
We can create a function that writes the Fibonacci series to an arbitrary boundary:
The keyword def
introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.
The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring. (More about docstrings can be found in the section Documentation Strings.) There are tools which use docstrings to automatically produce online or printed documentation, or to let the user interactively browse through code; it’s good practice to include docstrings in code that you write, so make a habit of it.
The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables and variables of enclosing functions cannot be directly assigned a value within a function (unless, for global variables, named in a global
statement, or, for variables of enclosing functions, named in a nonlocal
statement), although they may be referenced.
The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). 1 When a function calls another function, or calls itself recursively, a new local symbol table is created for that call.
A function definition associates the function name with the function object in the current symbol table. The interpreter recognizes the object pointed to by that name as a user-defined function. Other names can also point to that same function object and can also be used to access the function:
Coming from other languages, you might object that fib
is not a function but a procedure since it doesn’t return a value. In fact, even functions without a return
statement do return a value, albeit a rather boring one. This value is called None
(it’s a built-in name). Writing the value None
is normally suppressed by the interpreter if it would be the only value written. You can see it if you really want to using print()
:
It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:
This example, as usual, demonstrates some new Python features:
The
return
statement returns with a value from a function.return
without an expression argument returnsNone
. Falling off the end of a function also returnsNone
.The statement
result.append(a)
calls a method of the list objectresult
. A method is a function that ‘belongs’ to an object and is namedobj.methodname
, whereobj
is some object (this may be an expression), andmethodname
is the name of a method that is defined by the object’s type. Different types define different methods. Methods of different types may have the same name without causing ambiguity. (It is possible to define your own object types and methods, using classes, see Classes) The methodappend()
shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent toresult = result + [a]
, but more efficient.
4.8. More on Defining Functions
It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.
4.8.1. Default Argument Values
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
This function can be called in several ways:
giving only the mandatory argument:
ask_ok('Do you really want to quit?')
giving one of the optional arguments:
ask_ok('OK to overwrite the file?', 2)
or even giving all arguments:
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
This example also introduces the in
keyword. This tests whether or not a sequence contains a certain value.
The default values are evaluated at the point of function definition in the defining scope, so that
will print 5
.
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
This will print
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
4.8.2. Keyword Arguments
Functions can also be called using keyword arguments of the form kwarg=value
. For instance, the following function:
accepts one required argument (voltage
) and three optional arguments (state
, action
, and type
). This function can be called in any of the following ways:
but all the following calls would be invalid:
In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor
is not a valid argument for the parrot
function), and their order is not important. This also includes non-optional arguments (e.g. parrot(voltage=1000)
is valid too). No argument may receive a value more than once. Here’s an example that fails due to this restriction:
When a final formal parameter of the form **name
is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name
(described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (*name
must occur before **name
.) For example, if we define a function like this:
It could be called like this:
and of course it would print:
Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call.
Comments
Post a Comment