Learning Python - 6th day (Morning)

 I watched this awesome tutorial: Click here

Today I have learnt about new things. Yes completely new Python codes which are not even available in Java or C++. After this I love Python more than before.

I have learnt 3 things:

    1. Position:
            Yesterday I studied about functions more and more and I have got to know about an issue.
            Let's imagine, I have function called printNames(name1,name2)
            Let's say name 1 should be Harry
            And name 2 should be Steve
            So, the function and python code will be,
            
            def printNames(name1,name2):
                    print('Name 1 is: ', name1)
                    print('Name 2 is: ', name2)

            printNames('Harry','Steve')
            
             Output: Name 1 is: Harry
                            Name 2 is: Steve
            Here, if I suddenly put printNames('Steve', 'Harry') the output will be reversed as well. Name 1             will be Steve and name to will be Harry, which I don't want. So in order to maintain perfect                    output we need to take care of the position. 


     2. Keyword:
            Okay, I have learnt about position maintaining. But what if I don't know if first position is for name 1 or the second position is for name 1. To solve this problem, Keywords come in action. I am explaining this within less sentences:

Simply keyword means you need to mention the name of each arguments.
Example: 
 

            def printNames(name1,name2):
                    print('Name 1 is: ', name1)
                    print('Name 2 is: ', name2)

            printNames(name2='Steve', name1='Harry')

Output:    Name 1 is: Harry
                 Name 2 is: Steve


See, output is still the same. So we can ensure the perfect output even if I put arguments in wrong order with the help of keywords.

        3. Default: 
                 Now I know how to set arguments of a functions as I want. Every problem is solved, right? No brother, not yet! Let me tell you another issue with this. Look at the function again. The function printNames(name1,name2) expects 2 arguments or 2 names to be entered, right? 
What if I put only one name here? For example:  printNames(name1='Harry') 

The output will give me an error  with this code. Why this is happening? This is happening because there is no default value for each arguments in the function. The function does not know which value to use when there is no input from user. So, we need to set a default value for the function like this:

            def printNames(name1 = 'No Input', name2 = 'No Input'):
                    print('Name 1 is: ', name1)
                    print('Name 2 is: ', name2)

So now If I put 

            printNames(name2='Steve')

Output will be: Name 1 is: No Input 
                           Name 2 is: Steve

More about arguments: 

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:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

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

i = 5

def f(arg=i):
    print(arg)

i = 6
f()

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:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

This will print

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

4.8.2. Keyword Arguments

Functions can also be called using keyword arguments of the form kwarg=value. For instance, the following function:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

accepts one required argument (voltage) and three optional arguments (stateaction, and type). This function can be called in any of the following ways:

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

but all the following calls would be invalid:

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument

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:

>>>
>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'

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:

def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

It could be called like this:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

and of course it would print:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

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

Popular posts from this blog

Husband's Affair with Step Daughter Ends in Grisly Murder (True Crime Documentary)