Saturday, June 16, 2018

python chap 12 (hi friends checkout my previous lessons to learn from start)

Function

It is also possible to define function with variable number of arguments this are the forms as

Default Argument Values

  In here we specify a default value for one or more arguments this how we can call a function with fewer arguments this creates a function that can be called with fewer arguments than it is defined to allow like :


def myfun(fight,leavestep = 4, sail = 'boat'):
    while True:
        ok = input(fight)
        if ok in ('sword','knife','gun'):
            return True
        if ok in ('no','pain','gain'):
            return False
        if leavestep <= 0:
            raise ValueError ('invalid user response')
        print(sail)         
The function can be called in several ways such as
  • giving only mandatory argument like myfun('tool to fight') :
>>> myfun('tool to fight')
tool to fight sword
True
  • or we can give one of the optional arguments like in here myfun('tool to fight',1):
>>> myfun('tool to fight',1)
tool to fightno
False
  • or even giving all the arguments as as myfun('tool to fight',1,'ship')

>>>myfun('tool to fight',1,'ship')
tool to fight
ship
Now here are given the ways first we give the first compulsary argument because in the function it is only without value so we have to give it a value in calling function and by running the code and writing the input we get the values as the process in the function and also can apply all three arguments can also get errors according to the value in the second argument we get as for example here is myfun('tool to fight',0,'ship')
>>> myfun('tool to fight',0,'ship')
tool to fight
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    myfun('tool to fight',0,'ship')
  File "<pyshell#38>", line 10, in myfun
    raise ValueError ('invalid user response')
ValueError: invalid user response
Note: The default value are evaluated at the function definition at the defining scope so that

>>> i = 5
>>> def by(arg = i):
    print(arg)

  
>>> i = 7
>>> by()
5
>>>
it will output 5
This here one thing to note as Warning : is that the due to the fact that default value is evaluated only once so in the case of mutable objects such as lists dictionaries or instances of most classes the following function accumulates the arguments passed to it on subsequent calls as

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

>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
>>>
The result will be as given above to prevent from the default to be shared between subsequent calls you can write the function like this instead and the result will be also as given below
>>> def f(a,L=None):
 if L is None:
  L=[]
  L.append(a)
  return L

 
>>> print(f(1))
[1]
>>> print(f(2))
[2]
>>> 

Keyword Arguments

The keyword arguments are used to call functions in the form as kwargs = value for instance the function is given below

 def plane (power,state = 'a big',action = 'fly high',type = 'sea blue'):
    print("This place will",action,end='')
    print("if you put",power,"power through it")
    print("__ So swift , the",type)
    print("It's",state , "!")
Accepts one required argument power and optional three arguments like state , action, type we can call this function in any of the following ways like
//1 positional argument
plane(1000)
//1 keyword argument
plane(power=1000)
//2 keyword argument
plane(power=1000,action='fly low')
//2 keyword argument
plane(action = 'fly low',power=1000)
//3 positional arguments
plane('thousand','jumbo','fly low')
//1 positional and 1 keyword argument
plane('a ten thousand',state ='jumbo' )

but there are also some invalid calls like

//no compulsary argument
plane()
//non keyword argument after a keyword argument
plane(power=2000,'fly jump')
//duplicate value for the same argument
plane(2000,power=1000)
//unknown keyword argument
plane(speed = 12)
And in the final formal parameter in the form **name receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter and the formal parameter of the form *name may be combined with this which receives a tuple containing the positional arguments beyond the formal parameter list (*name must occur before **name) as

def grocery(kind,*quantity,**price):
    print("-- Do you have any ",kind,"?")
    print("--- Iam sorry we are all out of",kind)
    for arg in quantity:
        print(arg)
    print('-'* 40)
    for kw in price:
        print(kw,":",price[kw])
//result will be as
 grocery("broccoli",3,4,5,broccoligrade1 = 25,broccoligrade2 = 35,broccoligrade3 = 45)
-- Do you have any  broccoli ?
--- Iam sorry we are all out of broccoli
3
4
5
----------------------------------------
broccoligrade1 : 25
broccoligrade2 : 35
broccoligrade3 : 45

the point here to note is 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


Thats all for this post guys hope you like it to get latest lessons follow by email and share if you want to know more about other languages and my other works or have any doubts please follow and comment below

Sunday, June 10, 2018

python chap 11 (Hi friends this post is made as chapters so read the previous chapters for better understanding. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

break , continue statements  and else clause on loop

                               This statements are used as it describe break statement break out of the innermost enclosing for or while loop and the continue statement continue through the next iteration of the loop and the loop may have an else clause it is executed when the loop terminates through exhaustion of the list with for or when the condition becomes false with while loop but not when the loop is terminated by a break statement

for x in range(10,20):
        if x==15:
            print("no way for 15")
            break
        if x%2 == 0:
            print("found an even number")
            continue
        print(x," is a prime number")


for x in range(2,10):
    for l in range(5,x):
        if l == 7:
            print(x,"i got from seven to 10")
            break
    else:
       print(x,"i got from two to seven")

In this code we can clearly see the job done by each of the statements first the for loop iterates from 10 to 20 and it checks in the if statement that the iterating value in x is it equal to 15 and if it is equal then it will print "no way for 15" and break statement is done which will terminate the loop and if it is not equal to 15 then it will check in the second  if statement that x%2 is equal to zero if it is then it will print "found an even number" and then the continue statement will be done the continue statement continues with the next iteration of the loop. and if x%2 is not equal to zero then prints "x is a prime number"
And here in the next code block the first for loop iterates from 2 to 10 and each iteration from 5 there is another for loop which iterates to the value of x next to 5 and in that for loop if value is equal to 7 then it will print x"i got from seven to 10" and there is an else clause which prints from the beginning of the for loop from two to seven here one thing to note is the else clause is the else of the second for loop not the if statement

pass statement

The pass statement does nothing it is used when we need a statement syntactically but the program requires no action
while True:
          pass
This will make a busy wait for keyboard interrupt (ctrl+c) can also be used to create minimal classes like

class MyClass :
           pass


Another place where pass can be used is as a placeholder for a function or conditional body when you are working on new code allowing to thinking at a more abstract level the pass is silently ignored
def  myfunc(*args):
          pass #remember to implement this

Functions

function is a named code block of the program where a specific task is executed in python there are many built in functions like print().
  • the function starts with the keyword def 
  •  followed by a name will be given to the function the conventional style for naming of a function is like lower_case_with_underscore 
  • next comes the parenthesized list of formal parameters we can also define parameters inside this parenthesis and the code block in python starts with a colon (:) and is indented
  • in the first line of the body of the code block  can be an optional string literal this string literal is the functions documentation string or doc string  
  • And then the code is written for the specific task and the statement return [expression] exits the function optionally passing back an expression to the caller the return statement without an expression argument returns None Falling of the end of a function also returns None 

More on functions will be included in the next post Hope you like the post and if you have any doubts or suggestions include it in the comment section and don't forget to share and follow to get latest posts on this blog follow by email